有時候需要在視圖上添加虛線的分割線,要么讓美工切圖,要么就使用代碼,在網上找到一種別人寫的繪制虛線的方法,分享一下。
/**
** 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];
}