ios - 动画背景颜色变化 - 一侧到另一侧

标签 ios swift uiviewanimation

假设我有一个水平长的矩形。它是蓝色的。我想要它是红色的。但是,我希望颜色变化从一侧开始并在另一侧结束。

我可以使用关键帧动画使整个 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 。您可以为其位置颜色endPointstartPoint

设置动画

enter image description here

这是一个快速片段,您可以将其粘贴到 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/

相关文章:

ios - 如何实现一个动画队列,一个动画又一个动画结束

jQuery 单击在 iOS 中不起作用?

ios - TWTweetComposeViewController 中的错误?

swift - 始终在get方法中登录成功

ios - 无法将类型 'DateComponents' 的值分配给类型 'String?' 的值

ios - 如何取消 UIViews 基于 block 的动画?

ios - 自定义 uitableviewcell 突出显示颜色

iphone - Unity 应用程序在第一个场景中崩溃

SwiftUI 更新导航操作的状态

ios - 删除 UIBezierPath 上的多余空间