2016-04-29 16 views
2

Angenommen, ich habe ein Rechteck, das horizontal lang ist. Es ist blau. Ich möchte, dass es rot ist. Ich möchte jedoch, dass die Farbänderung auf der einen Seite beginnt und auf der anderen endet.Animieren der Hintergrundfarbenänderung - von Seite zu Seite

Ich kann eine Schlüsselbildanimation verwenden, um die ganze Ansicht allmählich von Rot zu Blau zu ändern. Gibt es eine Möglichkeit, es von links nach rechts/rechts-links zu verändern?

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

Antwort

3

Werfen Sie einen Blick auf CAGradientLayer. Sie können ihr locations, colors oder endPoint und startPoint

enter image description here

Hier animieren ist ein kurzer Schnipsel Sie in Spielplatz einfügen können und sehen, wie es funktionieren kann. In diesem Fall animiere ich die Farborte der Farbverläufe.

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

Swift 3-Version:

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 
Verwandte Themen