动画CALayer边框更改 [英] Animate CALayer border change

查看:51
本文介绍了动画CALayer边框更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过以下方式将边框的宽度和颜色设置为 UIView 子类:

I'm setting a border width and color to a UIView subclass this way:

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

我的问题是:我该如何制作动画?谢谢.

My question is: How can I animate this? Thanks.

推荐答案

borderColor borderWidth 都是可设置动画的属性,但是由于您是在外部的视图子类中执行此操作的一个UIView动画块,禁用了隐式动画(那些在更改值时自动发生的动画).

Both borderColor and borderWidth are animatable properties but since you are doing this in a view subclass outside of an UIView animation block, implicit animations (those that happen automatically when you change a value) are disabled.

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

If you want to animate these properties then you can do an explicit animation with a CABasicAnimation. Since you are animating two properties on the same layer, you can add them both to an animation group and only configure the duration, timing, etc. once. Note that the explicit animations are purely visual, the model value (the actual property) doesn't change when you add them. That is why you both configure the animation and set the model value.

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"];

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

If you look at the documentation for CABasicAnimation under the section "Setting Interpolation values", you will see that it's not necessary to specify both the toValue and the fromValue like I did, so the code could be made slightly shorter. However, for clarity and readability (especially when you are starting with Core Animation) being more explicit can help you (and your coworker) understand the code.

这篇关于动画CALayer边框更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆