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
屬性