UIImageView着色动画

5
这个之前的问题类似,我想给一个任意图片(一个UIImageView)应用任意颜色的色调。但是,我希望色调在N秒内逐渐消失,具有“脉冲”效果。我将每M秒触发一次脉冲。
虽然我认为我可以使用NSTimer来改变色调来构建一个天真的解决方案,但我认为我可能可以使用Core Animation框架来拥有一个更加优雅(和高效)的解决方案。但是,我对核心动画不是很熟悉。
使用Core Animation创建这样的“脉冲”是否可能?如果是,怎么做?
2个回答

2

虽然我有点晚了,但是我找到了一种使 UIImageViewtintColor 实现动画的方法。你只需要将 contentsMultiplyColor 作为 CABasicAnimationkeyPath 即可。例如:

// 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")

1
如果您计划使用核心动画,那么方法将与您链接到以前的SO问题所演示的不同。相反,创建一个使用所需色调的图层,然后对该图层的不透明度进行动画处理。类似于这样的东西:
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 中发生的混合情况。
最好的问候。
更新:找到另一个SO帖子,称在CA中混合取决于图层的“opaque”属性。

如果上述任意图像不是矩形的(比如圆形),或者只是周围有空白边框(透明度为0的像素),这个方法还能正常工作吗?因为如果你调用了setBackgroundColor:,你会给那些本来不应该被“点亮”的像素设置颜色。 - Shaggy Frog
没错,它将会给整个矩形着色。我认为这对于其他的核心图形方法也是适用的,但我不确定,因为我还没有尝试过。 - Matt Long
你可以给tintLayer添加一个mask。我正在尝试给UIImageView着色 - tintLayer.mask = imageView.layer可能会奏效。希望imageView.layer喜欢在两个地方使用。 - Rhythmic Fistman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接