用20行代码用动画实现一个旋转一圈的圆形

先来一张实际效果的预览

《用20行代码用动画实现一个旋转一圈的圆形》 2018-05-28 16_52_51.gif

实现这个效果只需要20多行代码哦

废话不多说,首先要画一个 layer

CAShapeLayer *processLayer = [CAShapeLayer layer];
[self.view.layer addSublayer:processLayer];
_processLayer = processLayer;
processLayer.frame = (CGRect){{self.view.bounds.size.width/2.0-100, self.view.bounds.size.height/2.0-100}, 200, 200};
processLayer.fillColor = [UIColor redColor].CGColor;

然后用CAKeyframeAnimation来做这个动画,keyFrame 的关键在于每帧的路径。这里的解决方法是用 for 循环来画每帧的扇形

(原理好像古人算圆周率的办法啊hhh)

NSInteger accuracy = 200;
NSMutableArray *pathArr = @[].mutableCopy;

CGFloat angle = 1.0/(CGFloat)(accuracy)*360.0;
CGFloat center = 100;
CGFloat radius = center;

for (NSInteger pos=0; pos<=accuracy; ++pos) {

    UIBezierPath *toPath = [UIBezierPath bezierPath];
    [toPath moveToPoint:CGPointMake(center, center)];

    for (NSInteger curretnPos = 0; curretnPos<=pos; ++curretnPos) {
        CGFloat radian = angle*(curretnPos - accuracy/4.0)  / 180.0 * M_PI;
        CGFloat x = center + radius * cos(radian);
        CGFloat y = center + radius * sin(radian);

        [toPath addLineToPoint:CGPointMake(x, y)];
    }

    [toPath closePath];
    [pathArr addObject:toPath.CGPath];
}

其中accuracy是精度,越高的精度生成的曲线就更圆,也会产生更多的帧,动画就越流畅,这里精度为200,即200帧

由于cos(0)和 sin(0)对应的其实是圆的最右边,为了让圆从顶部开始画,这里需要减掉1/4pi的角度

看到两层 for 循环是不是很不爽,那就来改进一下,把里面那层 for 循环改成直接画圆算了

NSInteger accuracy = 100;
NSMutableArray *pathArr = @[].mutableCopy;

CGFloat angle = 1.0/(CGFloat)(accuracy)*360.0;
CGFloat radius = 100;
CGFloat startAngle = angle*(0 - accuracy/4.0)/ 180.0 * M_PI;
CGPoint centerPoint = CGPointMake(processLayer.bounds.size.width/2.0, processLayer.bounds.size.height/2.0);
for (NSInteger pos=0; pos<=accuracy; ++pos) {

    UIBezierPath *toPath = [UIBezierPath bezierPath];

    [toPath moveToPoint:centerPoint];

    CGFloat endAngle = angle*(pos - accuracy/4.0)/ 180.0 * M_PI;

    [toPath addArcWithCenter:centerPoint radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES];


    [toPath closePath];

    [pathArr addObject:toPath.CGPath];
}

最后就是把动画应用到processLayer上了

CAKeyframeAnimation *animate = [CAKeyframeAnimation animationWithKeyPath:@"path"];
animate.removedOnCompletion = NO;
animate.duration = 2;
animate.fillMode = kCAFillModeForwards;
animate.values = pathArr;
animate.calculationMode = kCAAnimationDiscrete;

[processLayer addAnimation:animate forKey:@"animate"];

完成

上面说到accuracy越高的精度生成的曲线就更圆。那么反过来想,精度低的时候不就是多边形了吗?比如把accuracy改成10,就能画出10边形(虽然结果动画非常地不流畅)

《用20行代码用动画实现一个旋转一圈的圆形》 2018-05-28 17_19_10.gif

    原文作者:庄msia
    原文地址: https://www.jianshu.com/p/b1bde4e762f2
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞