ios画虚线

项目中用到了自己画的虚线,记录一下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {


// 画虚线

CAShapeLayer *shapeLayer = [CAShapeLayer layer];
[shapeLayer setFillColor:[[UIColor clearColor] CGColor]];

// 设置虚线颜色为blackColor
[shapeLayer setStrokeColor:[[UIColor colorWithHex:@"#dcd2de"] CGColor]];
[shapeLayer setStrokeColor:[[UIColor colorWithRed:223/255.0 green:223/255.0 blue:223/255.0 alpha:1.0f] CGColor]];

// 3.0f设置虚线的宽度
[shapeLayer setLineWidth:1.0f];
[shapeLayer setLineJoin:kCALineJoinRound];

// 8=线的宽度 3=每条线的间距
[shapeLayer setLineDashPattern:
[NSArray arrayWithObjects:[NSNumber numberWithInt:8],
[NSNumber numberWithInt:6],nil]];

// Setup the path
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, 25, 15);
CGPathAddLineToPoint(path, NULL, frame.size.width-25,15);
[shapeLayer setPath:path];
CGPathRelease(path);

// 可以把self改成任何你想要的UIView
[[self layer] addSublayer:shapeLayer];

}
return self;
}