如何为CAShapeLayer的填充设置动画?

时间:2015-11-13 16:47:20

标签: ios objective-c cashapelayer

我有一个圆形的CAShapeLayer,我希望动画填充。我创建了我的CAShapeLayer

- (void)viewDidLoad {
    [super viewDidLoad];

    // Filled layer
    CAShapeLayer *filledCircleShape = [CAShapeLayer new];
    filledCircleShape.frame = CGRectMake(100, 100, 100, 100);
    filledCircleShape.fillColor = [UIColor purpleColor].CGColor;
    filledCircleShape.strokeColor = [UIColor grayColor].CGColor;
    filledCircleShape.lineWidth = 2;
    filledCircleShape.path = [self filledBezierPathWithRelativeFill:.75 inFrame:filledCircleShape.frame].CGPath;
    [self.view.layer addSublayer:filledCircleShape];

    self.filleShapeLayer = filledCircleShape;
}

- (UIBezierPath *)filledBezierPathWithRelativeFill:(CGFloat)relativeFill
{
    UIBezierPath *filledCircleArc = [UIBezierPath bezierPath];
    CGFloat arcAngle = 2 * acos(1 - 2 * relativeFill); // 2arccos ((r - 2rp) / r) == 2 arccos(1 - 2p)
    CGFloat startAngle = (M_PI - arcAngle) / 2;
    CGFloat endAngle = startAngle + arcAngle;
    [filledCircleArc addArcWithCenter:self.boundsCenter radius:self.radius startAngle:startAngle endAngle:endAngle clockwise:YES];

    return filledCircleArc;
}

这看起来像这样: enter image description here

我尝试了以下操作,使其为路径更改设置动画。

- (void)animate
{
    UIBezierPath *toBezierPath = [self filledBezierPathWithRelativeFill:0.3 inFrame:CGRectMake(100, 100, 100, 100)];
    CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
    pathAnimation.duration = 5.f;
    pathAnimation.toValue = (__bridge id)toBezierPath.CGPath;
    [self.filleShapeLayer addAnimation:pathAnimation forKey:@"path"];
}

哪种作品。形状图层动画但看起来像这样

enter image description here

enter image description here

我希望形状图层像小时玻璃一样动画,从一个百分比开始,然后动画到另一个。

有关如何使用CAShapeLayer实现此目的的任何想法?

1 个答案:

答案 0 :(得分:1)

CAShapeLayer对填充物来说太过分了。它不会神奇地按照你想要的方式制作动画,无论如何它都是不必要的。从一个大的方形紫色视图开始并向下设置动画 - 但是放一个面具以便只能看到形状区域的内部 - 就像我在这里一样(除了我填充而不是清空):

enter image description here