动画UIImageView色调 [英] Animating a UIImageView tint
问题描述
类似于此先前的问题 ,我想将任意颜色的色调应用于任意图像( UIImageView
)。但是,我希望色调在N秒钟内消失,以产生脉冲效果。我将每M秒触发一次脉冲。
Similar to this previous question, I want to apply an arbitrarly-coloured tint to an arbitrary image (a UIImageView
). However, I want the tint to fade away over N seconds of time, to have a "pulse" effect. I'll be triggering the pulse every M seconds.
虽然我认为我可以使用 NSTimer
更改色彩,我想我可能可以使用某些Core Animation框架来拥有更优雅(更有效)的解决方案。但是,我对Core Animation不太熟悉。
While I think I could rig up a naive solution using an NSTimer
to change the tint, I think I can probably use some of the Core Animation framework to have a much more elegant (and efficient) solution. However, I'm not very familiar with Core Animation.
Core Animation是否可以创建像这样的脉冲?如果是这样,怎么办?
Is creating a "pulse" like this possible with Core Animation? If so, how?
推荐答案
如果您打算使用Core Animation,则该方法将与本教程中演示的方法不同。您到前一个SO问题的链接。而是创建一个使用您想要的颜色作为色调的图层,然后对该图层的不透明度进行动画处理。像这样:
If you're planning to use Core Animation, the approach will be different than what was demonstrated in your link to a previous SO question. Instead, create a layer that uses the color you're after for the tint and then animate that layer's opacity. Something like this:
CALayer *tintLayer = [CALayer layer];
// Center the layer on the view
[tintLayer setBounds:[imageView bounds]];
[tintLayer setPosition:CGPointMake([imageView bounds].size.width/2.0,
[imageView bounds].size.height/2.0)];
// Fill the color
[tintLayer setBackgroundColor:
[[UIColor colorWithRed:0.5 green:0.5 blue:0.0 alpha:1.0] CGColor]];
[tintLayer setOpacity:0.5];
[[imageView layer] addSublayer:tintLayer];
// Add the animation
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
[animation setFromValue:[NSNumber numberWithFloat:0.5]];
[animation setToValue:[NSNumber numberWithFloat:0.0]];
// Animate back to the starting value automatically
[animation setAutoreverses:YES];
// Animate over the course of 5 seconds.
[animation setDuration:5.0];
[tintLayer addAnimation:animation forKey:@"opacity"];
我不确定的唯一问题是它是否可以正常工作,因为我们不在着色层中指定混合模式。我将不得不看看默认情况下CA发生了什么混合。
The only question I'm not sure about is whether it will work the same since we don't specify a blend mode in the tint layer. I will have to look and see what blending is occurring by default with CA.
最好的问候。
更新:找到了另一篇SO 帖子,内容为CA取决于图层的不透明属性。
UPDATE: Found another SO post that says that blending in CA depends on the layer's 'opaque' property.
这篇关于动画UIImageView色调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!