假设我有一个水平长的矩形。它是蓝色的。我想要它是红色的。但是,我希望颜色变化从一侧开始并在另一侧结束。
我可以使用关键帧动画使整个 View 逐渐从红色变为蓝色。有没有办法逐渐从左右/右左改变?
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 }
})
最佳答案
看看CAGradientLayer 。您可以为其位置
、颜色
或endPoint
和startPoint
这是一个快速片段,您可以将其粘贴到 Playground 中并查看它是如何工作的。在本例中,我对渐变颜色位置进行动画处理。
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
关于ios - 动画背景颜色变化 - 一侧到另一侧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36944260/