UIBezierPath和CAShapeLayer结合绘制任意弧度的圆形(包含旋转动画)
jopen
9年前
首先来看一张要绘制弧度圆的图片,从图中可知中心点的坐标为(150,150),弧度的半径为75(radius),起始点为0°开始到135°,代码中的pi为3.14159265359,如下图所示:
来看一下具体是如何实现的,代码部分如下:
#import "ViewController.h" #define pi 3.14159265359 #define DEGREES_TO_RADIANS(degress) ((pi * degress)/180) @interface ViewController () @property (nonatomic,strong) CAShapeLayer *shapeLayer; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; CALayer *testLayer = [CALayer layer]; testLayer.backgroundColor = [UIColor clearColor].CGColor; testLayer.frame = CGRectMake(100, 100, 100, 100); [self.view.layer addSublayer:testLayer]; _shapeLayer = [CAShapeLayer layer]; _shapeLayer.fillColor = [UIColor clearColor].CGColor; _shapeLayer.strokeColor = [UIColor orangeColor].CGColor; _shapeLayer.lineCap = kCALineCapRound; _shapeLayer.lineWidth = 7; UIBezierPath *thePath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(50, 50) radius:50-3.5 startAngle:0 endAngle:DEGREES_TO_RADIANS(135) clockwise:YES]; _shapeLayer.path = thePath.CGPath; [testLayer addSublayer:_shapeLayer]; }查看一下运行效果:
根据要求,可以看到绘制出了一个135°角的弧度圆,接下来让这个弧度圆做一个简单的绕z轴旋转360°的动画。在最后面添加这句话,代码如下:
CABasicAnimation *animation = [CABasicAnimation animation]; animation.keyPath = @"transform.rotation.z"; animation.duration = 4.f; animation.fromValue = @(0); animation.toValue = @(2*M_PI); animation.repeatCount = INFINITY; [testLayer addAnimation:animation forKey:nil];看一下运行效果:
希望对你有帮助