Warm tip: This article is reproduced from serverfault.com, please click

ios-动画CALayer边框更改

(ios - Animate CALayer border change)

发布于 2014-02-21 07:27:42

通过这种方式子类设置边框的宽度和颜色UIView

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

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

Questioner
iOS Dev
Viewed
22
David Rönnqvist 2016-01-04 01:48:01

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

如果要设置这些属性的动画,则可以使用进行显式动画处理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"];

如果你在“设置插值值”部分下查看CABasicAnimation的文档,你会发现没有必要像我一样同时指定toValue和fromValue,因此可以将代码缩短一些。但是,为了清晰和易读(尤其是从Core Animation开始时),更加明确的做法可以帮助你(和你的同事)理解代码。