Dave
Dave

Reputation: 12206

Animating Background Color Change - Side to Side

Let's say I have a rectangle that is horizontally long. It's blue. I want it to be red. However, I want the color change to start on one side and end on the other.

I can use a key frame animation to make the whole view gradually change from red to blue. Is there a way to gradually change it from left-right/right-left??

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

Upvotes: 2

Views: 2335

Answers (2)

mcfroob
mcfroob

Reputation: 1154

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

Upvotes: 0

Nikola Lajic
Nikola Lajic

Reputation: 4075

Take a look at CAGradientLayer. You can animate its locations, colors or endPoint and startPoint

enter image description here

Here is a quick snippet you can paste into playground and see how it can work. In this case I'm animating the gradients color locations.

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

Upvotes: 3

Related Questions