【问题标题】:Create an animation when changing the path of a subLayer to another path将 subLayer 的路径更改为另一个路径时创建动画
【发布时间】:2026-01-13 19:35:01
【问题描述】:

我有一个UIView 及其层,我在其中添加了一个 CAShapeLayer 作为带有路径的子层。

当我点击UIButton 时,我将子图层的路径更改为另一条路径。

如何制作动画?

路径一改变就可以有动画吗?

我尝试添加:

let caAnimation = CABasicAnimation()
caAnimation.keyPath = "path"
caAnimation.duration = 2

shapeLayer.addAnimation(caAnimation, forKey: "path")

在我的UIViewinit(coder aDecoder: NSCoder) 方法中,以便在layoutSubviews() 方法中更改路径但不起作用时有动画。

我做错了什么?

编辑:

我添加了fromValuetoValue 作为动画的参数。我想知道我是否必须一直这样做,或者是否有一种方法可以在不指定 tofrom 值的情况下进行动画处理,并且它会自动获取更改前的值和更改后的值并制作动画。

【问题讨论】:

  • 你最终解决了这个问题吗?
  • 不,反正我不记得了。我做了其他事情。

标签: ios swift cabasicanimation


【解决方案1】:

它在objective-c中,但我想你会明白它的要点。

CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"path"];
anim.duration = 2.0;

UIBezierPath *path = myPath;
anim.fromValue = (__bridge id)layer.path;
anim.toValue = (__bridge id)path.CGPath;
layer.path = path.CGPath;
[layer addAnimation:anim forKey:@"path"];

如果我没记错的话,您也可以将 toValue 或 fromValue 保留为 nil,它会将其设置为当前值。

重要的是要注意设置图层的实际路径,这样在完成动画时它不会恢复到原来的状态。

【讨论】:

  • 好像不设置fromValuetoValue就不行