开发者

Animating a UIImageView tint

Similar to this previous question, I want to apply an arbitrarly-coloured tint to an arbitrary 开发者_Python百科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.

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.

Is creating a "pulse" like this possible with Core Animation? If so, how?


Late for party, but I've found way to animate UIImageView's tintColor. You just need to provide contentsMultiplyColor as keyPath for CABasicAnimation. Example:

// 5 seconds infinite pulse animation from current tintColor to red color
let basicAnimation = CABasicAnimation(keyPath: "contentsMultiplyColor")
basicAnimation.duration = 5.0 
basicAnimation.fromValue = imageView.tintColor.cgColor
basicAnimation.toValue = UIColor.red.cgColor
basicAnimation.autoreverses = true
basicAnimation.repeatCount = Float.infinity

imageView.layer.add(basicAnimation, forKey: "TintColorAnimationKey")


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

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.

Best regards.

UPDATE: Found another SO post that says that blending in CA depends on the layer's 'opaque' property.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜