带有来自 patternImage 的颜色的 CAKeyFrameAnimation

CAKeyFrameAnimation with Color from patternImage

我正在尝试使用 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");

}

有人有想法吗?

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

"bug"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);
}

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

@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
}