1. CAShaperLayer
CAShaperLayer是CALayer的子类,但是比CALayer更灵活,可以画出各种图形,步骤如下:
1、新建UIBezierPath对象bezierPath
2、新建CAShapeLayer对象caShapeLayer
3、将bezierPath的CGPath赋值给caShapeLayer的path,即 caShapeLayer.path = bezierPath.CGPath
4、把caShapeLayer添加到某个显示该图形的layer中
就像这样:
> _trackLayer = [CAShapeLayer layer];
_trackLayer.frame = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
_trackLayer.lineWidth = _lineWidth;
_trackLayer.strokeColor = _trackTintColor.CGColor;
_trackLayer.fillColor = self.backgroundColor.CGColor;
_trackLayer.lineCap = kCALineCapRound;
[self.layer addSublayer:_trackLayer];
创建之后会得到一个矩形,因为CAShapeLayer有个强大的属性path,用这个属性配合上UIBezierPath 这个类就可以达到神奇的效果.
用BezierPath构建一段弧线,你可以用任意条弧线来组成你想要的形状,设置颜色就不要用backgroundColor这个属性,而是用fillColor和strokeColor,前者代表设置layer的填充色,后者设置它的边框色
用贝塞尔曲线画一个圆,并将BezierPath的CGPath赋给CAShaperLayer的path
UIBezierPath *trackPath = [UIBezierPath bezierPath];
CGPoint center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);
CGFloat radius = (self.bounds.size.width - _lineWidth)/2;
[trackPath addArcWithCenter:center radius:radius startAngle:0 endAngle:2*M_PI clockwise:YES];
_trackLayer.path=trackPath.CGPath;
当然我们也可以给CAShapeLayer添加动画,通过给基本动画CABasicAnimation初始化及设置属性的方式
CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
rotationAnimation.toValue = [NSNumber numberWithFloat:M_PI*2];
rotationAnimation.duration = 1;
rotationAnimation.cumulative = YES;
rotationAnimation.repeatCount = HUGE_VALF;
[_progressLayer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
本文只是粗略的谈下CAShapeLayer和BezierPath的使用,并没有写完整的demo;
网友评论