【问题标题】:Animating Background Color Change - Side to Side动画背景颜色变化 - 并排
【发布时间】:2016-04-29 17:28:13
【问题描述】:

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

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

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

【问题讨论】:

    标签: ios swift uiviewanimation


    【解决方案1】:

    看看CAGradientLayer。您可以为其locationscolorsendPointstartPoint 设置动画

    这是一个快速的 sn-p,您可以将其粘贴到 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
    

    【讨论】:

      【解决方案2】:

      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
      

      【讨论】:

        猜你喜欢
        • 2013-07-28
        • 1970-01-01
        • 2015-08-11
        • 1970-01-01
        • 2017-12-10
        • 2011-02-06
        • 1970-01-01
        • 2012-06-13
        • 1970-01-01
        相关资源
        最近更新 更多