动画CALayer边框更改

iOS*_*Dev 31 objective-c calayer ios

我正在以这种方式将边框宽度和颜色设置为UIView子类:

- (void) setViewBorder
{
    self.layer.borderColor = [UIColor greenColor].CGColor;
    self.layer.borderWidth = 3.0f;
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:我怎样才能为此设置动画?谢谢.

Dav*_*ist 56

这两个borderColorborderWidth是动画的属性,但因为你是一个的UIView动画块外这样在视图中的子类,隐式动画(那些当您更改一个值,自动发生)被禁用.

如果要为这些属性设置动画,则可以使用a进行显式动画CABasicAnimation.由于您在同一图层上设置了两个属性的动画,因此可以将它们添加到动画组中,并仅配置一次持续时间,时间等.请注意,显式动画纯粹是可视化的,添加它们时模型值(实际属性)不会更改.这就是您配置动画和设置模型值的原因.

CABasicAnimation *color = [CABasicAnimation animationWithKeyPath:@"borderColor"];
// animate from red to blue border ...
color.fromValue = (id)[UIColor redColor].CGColor;
color.toValue   = (id)[UIColor blueColor].CGColor;
// ... and change the model value
self.layer.borderColor = [UIColor blueColor].CGColor;

CABasicAnimation *width = [CABasicAnimation animationWithKeyPath:@"borderWidth"];
// animate from 2pt to 4pt wide border ...
width.fromValue = @2;
width.toValue   = @4;
// ... and change the model value
self.layer.borderWidth = 4;

CAAnimationGroup *both = [CAAnimationGroup animation];
// animate both as a group with the duration of 0.5 seconds
both.duration   = 0.5;
both.animations = @[color, width];
// optionally add other configuration (that applies to both animations)
both.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

[self.layer addAnimation:both forKey:@"color and width"];
Run Code Online (Sandbox Code Playgroud)

如果您在"设置插值"部分下查看CABasicAnimation的文档,您将看到没有必要像我一样指定toValue和fromValue,因此可以稍微缩短代码.但是,为了清晰和可读性(特别是当您开始使用Core Animation时)更明确可以帮助您(和您的同事)理解代码.

  • @jrturton至于视图在`actionForLayer:forKey:`中实际做了什么,我能找到的最好[我的答案在这里](http://stackoverflow.com/a/21240400/608157)反过来引用[这个答案] (http://stackoverflow.com/a/4751531/608157).但是,您可以进行自己的实验,并在动画块的内部和外部询问图层委托(或直接查看视图)的"actionForLayer:forKey:"并查看您获得的响应.我不记得在某处正式记录它. (2认同)

Mes*_*ery 24

这是@David答案的快速解决方案:

let colorAnimation = CABasicAnimation(keyPath: "borderColor")
colorAnimation.fromValue = UIColor.red.cgColor
colorAnimation.toValue = UIColor.blue.cgColor
view.layer.borderColor = UIColor.blue.cgColor

let widthAnimation = CABasicAnimation(keyPath: "borderWidth")
widthAnimation.fromValue = 2
widthAnimation.toValue = 4
widthAnimation.duration = 4
view.layer.borderWidth = 4

let bothAnimations = CAAnimationGroup()
bothAnimations.duration = 0.5
bothAnimations.animations = [colorAnimation, widthAnimation]
bothAnimations.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)

view.layer.add(bothAnimations, forKey: "color and width")
Run Code Online (Sandbox Code Playgroud)


inf*_*783 9

如果你只想淡入边框,你也可以这样做:

UIView.transition(with: self, duration: 0.3, options: .transitionCrossDissolve, animations: {

        self.layer.borderColor = UIColor.green.cgColor
        self.layer.borderWidth = 3

}, completion: nil)
Run Code Online (Sandbox Code Playgroud)