动画背景颜色变化 - 左右

时间:2016-04-29 17:28:14

标签: ios swift uiviewanimation

假设我有一个横向长的矩形。它是蓝色的。我希望它是红色的。但是,我希望颜色更改从一侧开始,另一侧结束。

我可以使用关键帧动画使整个视图逐渐从红色变为蓝色。有没有办法从左右/右左逐渐改变它?

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

Swift 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