CAShapeLayer在初始化时也需要给一个frame值,但是,它本身没有形状,它的形状来源于你给定的一个path,然后它去取CGPath值,它与CALayer有着很大的区别
CAShapeLayer有着几点很重要:
1. 它依附于一个给定的path,必须给与path,而且,即使path不完整也会自动首尾相接
2. strokeStart以及strokeEnd代表着在这个path中所占用的百分比
3. CAShapeLayer动画仅仅限于沿着边缘的动画效果,它实现不了填充效果
给定一个指定的Path:
/ // 贝塞尔曲线(创建一个圆)
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(100 / 2.f, 100 / 2.f)
radius:50
startAngle:0
endAngle:M_PI * 2
clockwise:YES];
可以使用UIBezierPath 绘画出其它的图形 。
// 创建一个shapeLayer
CAShapeLayer *layer = [CAShapeLayer layer];
// layer.frame = self.bounds; // 与showView的frame一致
layer.strokeColor = [UIColor greenColor].CGColor; // 边缘线的颜色
layer.fillColor = [UIColor clearColor].CGColor; // 闭环填充的颜色
layer.lineCap = kCALineCapRound; // 边缘线的类型
layer.path = path.CGPath; // 从贝塞尔曲线获取到形状
layer.lineWidth = 3; // 线条宽度
layer.strokeEnd = 0.0;
// 将layer添加进图层
[self.layer addSublayer:layer];
设置动画使用 strokeEnd 属性
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
pathAnimation.duration = 1.0;
pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
pathAnimation.repeatCount=INT32_MAX;
pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
[layer addAnimation:pathAnimation forKey:nil];
layer.strokeEnd = 1;