我正在尝试使用CAKeyFrameAnimation为CALayer的backgroundColor设置动画。
当我用经典颜色制作时,它有效;但是使用从patternImage UIColor(patternImage:"imageName").CGColor
生成的Color,它根本不起作用。
@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");
}
有人有想法吗?
是不是可以这样做,还是我做错了什么?
" bug"的测试用例https://github.com/lastMove/patternBugDemo
答案 0 :(得分:1)
我不知道为什么将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);
}
编辑:以下是另一种解决方法:继续使用图层背景颜色,但使用计时器直接更改它:
@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
}