整理了一個方法,可以直接繪制虛線,下面直接上代碼。參數說明已經給出,可直接copy使用
/**
** lineView: 需要繪制成虛線的view
** lineLength: 虛線的寬度
** lineSpacing: 虛線的間距
** lineColor: 虛線的顏色
**/
+ (void)drawDashLine:(UIView *)lineView lineLength:(int)lineLength lineSpacing:(int)lineSpacing lineColor:(UIColor *)lineColor
{
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
[shapeLayer setBounds:lineView.bounds];
[shapeLayer setPosition:CGPointMake(CGRectGetWidth(lineView.frame) / 2, CGRectGetHeight(lineView.frame))];
[shapeLayer setFillColor:[UIColor clearColor].CGColor];
// 設置虛線顏色為blackColor
[shapeLayer setStrokeColor:lineColor.CGColor];
// 設置虛線寬度
[shapeLayer setLineWidth:CGRectGetHeight(lineView.frame)];
[shapeLayer setLineJoin:kCALineJoinRound];
// 設置線寬,線間距
[shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:lineLength], [NSNumber numberWithInt:lineSpacing], nil]];
// 設置路徑
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, 0, 0);
CGPathAddLineToPoint(path, NULL, CGRectGetWidth(lineView.frame), 0);
[shapeLayer setPath:path];
CGPathRelease(path);
// 把繪制好的虛線添加上來
[lineView.layer addSublayer:shapeLayer];
}