Gradually change background color in Swift

时光毁灭记忆、已成空白 提交于 2019-12-07 02:40:13

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/32287237/gradually-change-background-color-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!