2016-04-29 43 views
2

比方說,我有一個水平長的矩形。這是藍色的。我想它是紅色的。但是,我希望顏色變化從一側開始,另一側結束。動畫背景顏色變化 - 左右對角

我可以使用關鍵幀動畫使整個視圖從紅色逐漸變爲藍色。有沒有辦法逐步從左/右/左 - 左改變?

UIView.animateKeyframesWithDuration(2.0 /*Total*/, delay: 0.0, options: UIViewKeyframeAnimationOptions.CalculationModeLinear, animations: { 
    UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 1/1, animations:{ 
     self.view.backgroundColor = UIColor.redColor()  
     self.view.layoutIfNeeded() 
    }) 
    }, 
    completion: { finished in 
     if (!finished) { return } 
}) 

回答

3

看看CAGradientLayer。您可以用動畫的locationscolorsendPointstartPoint

enter image description here

這裏是一個快速片段可以粘貼到操場上,看看它如何工作。在這種情況下,我正在爲漸變顏色位置設置動畫。

import UIKit 
import XCPlayground 

XCPlaygroundPage.currentPage.needsIndefiniteExecution = true 

let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 400)) 

let startLocations = [0, 0] 
let endLocations = [1, 2] 

let layer = CAGradientLayer() 
layer.colors = [UIColor.redColor().CGColor, UIColor.blueColor().CGColor] 
layer.frame = view.frame 
layer.locations = startLocations 
layer.startPoint = CGPoint(x: 0.0, y: 1.0) 
layer.endPoint = CGPoint(x: 1.0, y: 1.0) 
view.layer.addSublayer(layer) 

let anim = CABasicAnimation(keyPath: "locations") 
anim.fromValue = startLocations 
anim.toValue = endLocations 
anim.duration = 2.0 
layer.addAnimation(anim, forKey: "loc") 
layer.locations = endLocations 

XCPlaygroundPage.currentPage.liveView = view 
0

斯威夫特3版本:

import UIKit 
import PlaygroundSupport 

PlaygroundPage.current.needsIndefiniteExecution = true 


let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 400)) 

let startLocations = [0, 0] 
let endLocations = [1, 2] 

let layer = CAGradientLayer() 
layer.colors = [UIColor.red.cgColor, UIColor.blue.cgColor] 
layer.frame = view.frame 
layer.locations = startLocations as [NSNumber]? 
layer.startPoint = CGPoint(x: 0.0, y: 1.0) 
layer.endPoint = CGPoint(x: 1.0, y: 1.0) 
view.layer.addSublayer(layer) 

let anim = CABasicAnimation(keyPath: "locations") 
anim.fromValue = startLocations 
anim.toValue = endLocations 
anim.duration = 2.0 
layer.add(anim, forKey: "loc") 
layer.locations = endLocations as [NSNumber]? 

PlaygroundPage.current.liveView = view