1. CAShaperLayer
先简单的介绍下CAShapeLayer
- CAShapeLayer继承自CALayer,可使用CALayer的所有属性
- CAShapeLayer需要和贝塞尔曲线配合使用才有意义。
- 使用CAShapeLayer与贝塞尔曲线可以实现不在view的DrawRect方法中画出一些想要的图形
关于CAShapeLayer和DrawRect的比较
DrawRect:DrawRect属于CoreGraphic框架,占用CPU,消耗性能大
CAShapeLayer:CAShapeLayer属于CoreAnimation框架,通过GPU来渲染图形,节省性能。动画渲染直接提交给手机GPU,不消耗内存
贝塞尔曲线与CAShapeLayer的关系
1,CAShapeLayer中shape代表形状的意思,所以需要形状才能生效
2,贝塞尔曲线可以创建基于矢量的路径
3,贝塞尔曲线给CAShapeLayer提供路径,CAShapeLayer在提供的路径中进行渲染。路径会闭环,所以绘制出了Shape
4,用于CAShapeLayer的贝塞尔曲线作为Path,其path是一个首尾相接的闭环的曲线,即使该贝塞尔曲线不是一个闭环的曲线
总结:形状由贝塞尔曲线决定,过程由strokeStart
,strokeEnd
决定。可以使用timer,slider,动画等改变数值进行控制。
2. 加载框
先上效果图:
效果图1再上代码:
- (void)initSubLayer:(CGRect)frame
{
CAReplicatorLayer *replicatorLayer = [CAReplicatorLayer layer];
replicatorLayer.frame = frame;
//延迟的时间
replicatorLayer.instanceDelay = 0.6 / 5;
//重复个数
replicatorLayer.instanceCount = 5;
//间隔
replicatorLayer.instanceTransform = CATransform3DMakeTranslation(10,0,0);
CAShapeLayer *shape = [CAShapeLayer layer];
shape.frame = CGRectMake(0, 0, 3,40);
shape.lineWidth = 3;
shape.lineCap = kCALineCapRound;
shape.strokeColor = [UIColor redColor].CGColor;
UIBezierPath* path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(1.5, 0)];
[path addLineToPoint:CGPointMake(1.5, shape.frame.size.height)];
shape.path = path.CGPath;
[shape addAnimation:[self extendAnimation] forKey:@"scaleAnimation"];
[replicatorLayer addSublayer:shape];
[self.layer addSublayer:replicatorLayer];
}
- (CABasicAnimation*)extendAnimation
{
CABasicAnimation *scale = [CABasicAnimation animationWithKeyPath:@"transform"];
scale.fromValue = [NSValue valueWithCATransform3D:CATransform3DScale(CATransform3DIdentity, 1.0, 1.0, 0.0)];
scale.toValue = [NSValue valueWithCATransform3D:CATransform3DScale(CATransform3DIdentity, 1, 1.0/5, 0.0)];
scale.autoreverses = YES;
scale.repeatCount = HUGE;
scale.duration = 0.6;
return scale;
}
在分析思路:
- 创建一个CAShapeLayer的条条,方式不限
- 加入动画改变scale的高度
- CAReplicatorLayer复制为多个
3. 跳过框
使用场景之一:
示例图先上效果图
效果图2再上代码
CGFloat radius =ceil(MIN(frame.size.width, frame.size.height)) / 2;
self.shapeLayer = [CAShapeLayer layer];
self.shapeLayer.fillColor = [[UIColor blackColor] colorWithAlphaComponent:0.2].CGColor;
//设置线条的宽度和颜色
self.shapeLayer.lineWidth = 2.0f;
self.shapeLayer.strokeColor = [UIColor redColor].CGColor;
//设置stroke起始点
self.shapeLayer.strokeStart = 0;
self.shapeLayer.strokeEnd = 1;
//创建出圆形贝塞尔曲线
UIBezierPath* circlePath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(radius, radius) radius:radius startAngle: -M_PI_2 endAngle: -M_PI_2 + 0.00000001 clockwise:NO];
self.shapeLayer.path = circlePath.CGPath;
[self.layer addSublayer:self.shapeLayer];
- (void)startAnimation {
CABasicAnimation* animation =[CABasicAnimation animationWithKeyPath:@"strokeEnd"];
animation.duration = 2;
animation.toValue = @0;
[self.shapeLayer addAnimation:animation forKey:nil];
}
再分析思路:
- 创建一个CAShapeLayer的圆形
- 设置好起始的角度
- 添加动画改变
strokeEnd
属性
网友评论