首页 文章

如何设置CAShapeLayer的填充动画?

提问于
浏览
2

我有一个圆形的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 回答

  • 1

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

    enter image description here

相关问题