gpt4 book ai didi

ios - 带有来自 patternImage 的颜色的 CAKeyFrameAnimation

转载 作者:可可西里 更新时间:2023-11-01 02:23:01 24 4
gpt4 key购买 nike

我正在尝试使用 CAKeyFrameAnimation 为 CALayer 的 backgroundColor 设置动画。当我用经典颜色制作它时,它会起作用;但是对于从 patternImage UIColor(patternImage:"imageName").CGColor 生成的颜色,它根本不起作用。

@IBAction func animFirstView(sender: AnyObject)
{
addAnim(view1, colors: [UIColor.blackColor().CGColor, UIColor.redColor().CGColor]) // THAT WORKS

}

@IBAction func animSecondView(sender: AnyObject)
{

var firstColor = UIColor(patternImage: UIImage(named:"stars1")!).CGColor;
addAnim(view2,
colors: [firstColor]); // THAT doesn't works at all :(
}

func addAnim(view:UIView, colors:[CGColor])
{
let anim = CAKeyframeAnimation(keyPath:"backgroundColor")
anim.values = colors;
anim.keyTimes = [0.0, 0.25, 0.5, 0.75, 1];
anim.calculationMode = kCAAnimationDiscrete
anim.duration = 0.3;
anim.repeatCount = Float.infinity;
view.layer.addAnimation(anim, forKey: "backgroundColor");

}

有人有想法吗?

难道不能这样做还是我做错了什么?

“错误”的测试用例 https://github.com/lastMove/patternBugDemo

最佳答案

我不知道为什么将 backgroundColor 设置为图案颜色作为关键帧动画的一部分不起作用。我通过模仿 my own existing example 解决了这个问题我将 contents 设置为关键帧动画:

@IBAction func animSecondView(sender: AnyObject)
{
var firstColor = UIColor(patternImage: UIImage(named:"stars1")!)
var secondColor = UIColor(patternImage: UIImage(named:"stars2")!)
addAnim(view2,
colors: [firstColor, secondColor, firstColor, secondColor]);
}

func addAnim(view:UIView, colors:[UIColor])
{
let anim = CAKeyframeAnimation(keyPath:"contents")
anim.values = colors.map {
col in
UIGraphicsBeginImageContextWithOptions(view.bounds.size, true, 0)
col.setFill()
UIBezierPath(rect: view.bounds).fill()
let im = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return im.CGImage
}
anim.keyTimes = [0.0, 0.25, 0.75, 1.0];
anim.calculationMode = kCAAnimationDiscrete
anim.duration = 1;
anim.repeatCount = Float.infinity;
view.layer.addAnimation(anim, forKey: nil);
}

enter image description here

编辑:这是另一种解决方法:继续使用图层背景颜色,但使用计时器直接更改它:

@IBOutlet weak var view2: UIView!
var colors = [UIColor]()
var timer : NSTimer!
var second = false

@IBAction func animSecondView(sender: AnyObject)
{
var firstColor = UIColor(patternImage: UIImage(named:"stars1")!)
var secondColor = UIColor(patternImage: UIImage(named:"stars2")!)
self.colors = [firstColor, secondColor]
if let timer = self.timer {
timer.invalidate()
}
self.timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "anim:", userInfo: nil, repeats: true)
}
func anim(t:NSTimer) {
view2.layer.backgroundColor = self.colors[self.second ? 1 : 0].CGColor
self.second = !self.second
}

关于ios - 带有来自 patternImage 的颜色的 CAKeyFrameAnimation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29802607/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com