CALayer不透明度动画 [英] CALayer opacity animation

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

问题描述

我想创建一种CALayer动画,这种动画具有某种浮华"的效果.为此,我试图设置"opacity"属性的动画,但是我的问题是我不知道从哪里开始以及如何做.

I want to create a CALayer animation that gives sort of a 'flashy' effect. For that I'm trying to animate the 'opacity' property, but my problem is that I have no idea where to start and how to do it.

以下是动画的图形说明:

Here is a graphical explanation of the animation:

opacity
   |    ___
1  |   |   |
   |   |   |    * repeatCount
0  |___|   |_ . . .
   -------------------------> time
    |______|
    duration

不透明度从0开始,然后设置为1动画,然后再次设置为0(此0比1到0动画耗时等于持续时间的秒数).然后,将这个过程重复"repeatCount"次.

The opacity starts at 0, then animates to 1, then to 0 again (this 0-to-1-to-0 animation takes a number of seconds equal to duration). Then this process is repeated 'repeatCount' times.

以下是代码的背景:

float duration = ...; // 0.2 secs, 1 sec, 3 secs, etc
int repeactCount = ...; // 1, 2, 5, 6, ect

CALayer* layer = ...; // I have a CALayer from another part of the code
layer.opacity = 0;

// Animation here

done = YES; // IN THE END of the animation set this ivar to yes

完成此任务的最佳方法是什么?我以前从未使用过CALayers,因此这也是学习其动画系统如何工作的好机会.顺便说一句,我已经搜索了文档,并且了解了如何添加一个或两个简单的动画,但是我不知道如何制作这个特定的动画.

What is the best way to accomplish this? I have never used CALayers before, so this is also a good opportunity to learn how their animation system works. By the way, I have searched the docs and I understand how you add one or two simple animations, but I have no idea how to do this particular one.

推荐答案

达到此目的的最佳方法是使用显式动画(请参见

The best way to accomplish this is to use an explicit animation (see guide) by creating an instance of CABasicAnimation and adding it to the layer.

代码看起来像这样:

CABasicAnimation *flash = [CABasicAnimation animationWithKeyPath:@"opacity"];
flash.fromValue = [NSNumber numberWithFloat:0.0];
flash.toValue = [NSNumber numberWithFloat:1.0];
flash.duration = 1.0;        // 1 second
flash.autoreverses = YES;    // Back
flash.repeatCount = 3;       // Or whatever

[layer addAnimation:flash forKey:@"flashAnimation"];

如果您想知道动画何时完成,可以设置一个委托并实现animationDidStop:finished:方法,但是最好使用完成块,因为它允许所有代码都放在同一位置.如果您是为iOS 4或OS X编写的,则可以使用出色的 CAAnimationBlocks 类别来实现.

If you want to know when the animation is done you can set a delegate and implement the animationDidStop:finished: method, however it's best to use a completion block as that allows all the code to be in the same place. If you are writing for iOS 4 or OS X then you can use the excellent CAAnimationBlocks category to accomplish this.

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

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