我正在尝试使用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的测试用例

最佳答案

我不知道为什么将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
}

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

10-11 08:46