項目中經(jīng)常有虛線的需求释树,現(xiàn)整理一部分伍伤,不足之處再修改
方形虛線:
/**
** lineView: 需要繪制成方形虛線的view
** lineLength: 虛線的寬度
** lineSpacing: 虛線的間距
** lineColor: 虛線的顏色
**/
-(void)drawSquareDottedLine:(UIView*)squareView lineLength:(int)lineLength lineSpacing:(int)lineSpacing lineColor:(UIColor*)lineColor
{
CAShapeLayer *border = [CAShapeLayer layer];
border.strokeColor = lineColor.CGColor;
border.fillColor = nil;
border.path = [UIBezierPath bezierPathWithRect:squareView.bounds].CGPath;
border.frame = squareView.bounds;
border.lineWidth = 1.0f;
border.lineCap = @"square";
border.lineDashPattern = @[@(lineLength), @(lineSpacing)];
[squareView.layer addSublayer:border];
}
虛線:
/**
** 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];
}