方法:
新建一个类(例如DashLine)继承UIView,,在其类中写入以下代码
/// 将当前线绘制成虚线
/// @param lineLength 虚线的宽度
/// @param lineSpacing 虚线的间距
/// @param lineColor 虚线的颜色
/// @param isHorizonal 虚线的方向 YES 为水平方向,NO 为垂直方向
- (void)drawDashedWithLineLength:(NSInteger)lineLength lineSpacing:(NSInteger)lineSpacing lineColor:(UIColor *)lineColor lineDirection:(BOOL)isHorizonal {
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
[shapeLayer setBounds:self.bounds];
if (isHorizonal) {
[shapeLayer setPosition:CGPointMake(CGRectGetWidth(self.frame) / 2, CGRectGetHeight(self.frame))];
} else {
[shapeLayer setPosition:CGPointMake(CGRectGetWidth(self.frame) / 2, CGRectGetHeight(self.frame) / 2)];
}
[shapeLayer setFillColor:[UIColor clearColor].CGColor];
// 设置虚线颜色
[shapeLayer setStrokeColor:lineColor.CGColor];
// 设置虚线宽度
if (isHorizonal) {
[shapeLayer setLineWidth:CGRectGetHeight(self.frame)];
} else {
[shapeLayer setLineWidth:CGRectGetWidth(self.frame)];
}
[shapeLayer setLineJoin:kCALineJoinRound];
// 设置线宽,线间距
[shapeLayer setLineDashPattern:@[[NSNumber numberWithInteger:lineLength], [NSNumber numberWithInteger:lineSpacing]]];
// 设置路径
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, 0, 0);
if (isHorizonal) {
CGPathAddLineToPoint(path, NULL,CGRectGetWidth(self.frame), 0);
} else {
CGPathAddLineToPoint(path, NULL, 0, CGRectGetHeight(self.frame));
}
[shapeLayer setPath:path];
CGPathRelease(path);
// 把绘制好的虚线添加上来
[self.layer addSublayer:shapeLayer];
}
调用:
Dashline *line = [[Dashline alloc] initWithFrame:CGRectMake(0, 0, 100, 0.5)];
//调用方法
[line drawDashedWithLineLength:2 lineSpacing:2 lineColor:[UIColor blackColor] lineDirection:YES];
[self addSubview:line];