Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gradually change background color in Swift

I'm making a game where I need the background color to change slowly. As the user plays the level, the background color should be changing to show progress.

I was thinking of having the starting color be light blue, and then changing to green, then yellow, then orange or something like that over time.

Any ideas?

like image 599
Nick Pacini Avatar asked Aug 29 '15 14:08

Nick Pacini


2 Answers

Here's a working example, just change the colors:

var backgroundColours = [UIColor()]
var backgroundLoop = 0

override func viewDidLoad() {
    super.viewDidLoad()
    backgroundColours = [UIColor.redColor(), UIColor.blueColor(), UIColor.yellowColor()]
    backgroundLoop = 0
    self.animateBackgroundColour()
}

func animateBackgroundColour () {
    if backgroundLoop < backgroundColours.count - 1 {
        backgroundLoop++
    } else {
        backgroundLoop = 0
    }
        UIView.animateWithDuration(1, delay: 0, options: UIViewAnimationOptions.AllowUserInteraction, animations: { () -> Void in
            self.view.backgroundColor =  self.backgroundColours[self.backgroundLoop];
        }) {(Bool) -> Void in
            self.animateBackgroundColour();
        }
}

This will cycle through colors endlessly, so you change up the looping mehanism, and the method will continuously call itself until you issue a command to remove all animations.

like image 84
Larry Pickles Avatar answered Nov 14 '22 16:11

Larry Pickles


first:

Create a view (or a box) set it to fill the screen; lets call it background
set its color to #e0f1f8 (light-blue)

Next: This code should get one started -

      UIView.animateWithDuration(0.5, animations: { () -> Void in
        background.Color = UIColor(red: 238/255.0, green: 238/255.0, blue: 80/255.0, alpha: 1.0)
      })

      UIView.animateWithDuration(0.5, animations: { () -> Void in
        background.Color = UIColor.redColor
      })

Hope this helps. Good luck!

Credit goes to:

Source for my Answer

like image 39
FujiRoyale Avatar answered Nov 14 '22 16:11

FujiRoyale