OGeek|极客世界-中国程序员成长平台

标题: ios - 如何为 CAShapeLayer 的填充设置动画? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 11:46
标题: ios - 如何为 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 *)filledBezierPathWithRelativeFillCGFloat)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 实现这一点的任何想法?



Best Answer-推荐答案


CAShapeLayer 对于填充来说太过分了。它不会神奇地以您想要的方式制作动画,而且无论如何也没有必要。只需从一个大的紫色方形 View 开始并向下设置动画——但放置一个蒙版,以便只有形状区域的内部可见——就像我在这里所做的那样(除了我正在填充而不是清空):

enter image description here

关于ios - 如何为 CAShapeLayer 的填充设置动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33697755/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4