一、CAShapeLayer的介绍
CAShapeLayer继承与CALayer,CALayer在创建时需要赋给frame,并且其形状是矩形的,而CAShapeLayer 的形状是根据特定的path(CGPathRef)来决定的
二、CAShapeLayer 的常用属性
以下属性是给已存在的layer设置属性的,如宽度,边角类型,拐角类型,颜色等
- 1.
@property(nullable) CGPathRef path;:决定layer的形状 - 2.
@property(nullable) CGColorRef fillColor;:决定layer的填充颜色 - 3.
@property(nullable) CGColorRef strokeColor;:决定layer的线条颜色 - 4.
@property CGFloat strokeEnd;:线条的结束位置(0~1,对应于path而言,默认为1) - 5.
@property CGFloat strokeStart;:线条的起始位置(0~1,对应于path而言,默认为0)
strokeEnd和strokeStart可以用来做动画,进度条动画就是用了CAShapeLayer的这两个属性来做的,keyPath为@"strokeEnd"
- 6.
@property(copy) NSString *lineCap;:path端点样式字符串常量,有3种样式
NSString *const kCALineCapButt, // 无端点
NSString *const kCALineCapRound, // 圆形端点
NSString *const kCALineCapSquare // 方形端点(样式上和kCGLineCapButt是一样的,但是比kCGLineCapButt长一点) - 7.
@property(copy) NSString *lineJoin;:拐角样式字符串常量,有3种样式
NSString *const kCALineJoinMiter, // 尖角
NSString *const kCALineJoinRound, // 圆角
NSString *const kCALineJoinBevel // 缺角 - 8.
miterLimit:最大斜接长度(只有在使用kCALineJoinMiter是才有效), 边角的角度越小,斜接长度就会越大,为了避免斜接长度过长,使用lineLimit属性限制,如果斜接长度超过miterLimit,边角就会以KCALineJoinBevel类型来显示 - 9.
@property(nullable, copy) NSArray<NSNumber *> *lineDashPattern;:虚线数组 - 10.
@property CGFloat lineDashPhase;:虚线的起始位置
示例,path是一条圆环的贝塞尔曲线
设置边角类型为自然类型
设置拐角类型为圆角
设置线条宽度为20像素
填充颜色为透明,线条颜色为黑色
线条终点为0.5(即一半),线条起点默认为0
虚线数组如下,虚线宽度2,5,10,循环交替
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(200, 200) radius:100 startAngle:0 endAngle:M_PI * 2 clockwise:YES];
self.layer.path = path.CGPath;
self.layer.lineCap = kCALineCapButt;
self.layer.lineJoin = kCALineJoinRound;
self.layer.lineWidth = 20;
self.layer.strokeColor = [UIColor blackColor].CGColor;
self.layer.fillColor = [UIColor clearColor].CGColor;
self.layer.strokeEnd = 0.5;
self.layer.lineDashPattern = @[@2, @5, @10];
[self.view.layer addSublayer:self.layer];
示例图样
三、使用
1.创建path,可以用CGPathRef直接创建,也可以用封装好的path来创建,如UIBezierPath
2.设置layer的属性
3.将layer添加到view的layer层上










网友评论