【问题标题】:Gradually change background color in Swift在 Swift 中逐渐改变背景颜色
【发布时间】:2015-08-29 14:40:09
【问题描述】:

我正在制作一个需要缓慢改变背景颜色的游戏。当用户玩关卡时,背景颜色应该会改变以显示进度。

我正在考虑让起始颜色为浅蓝色,然后随着时间的推移变为绿色、黄色、橙色或类似的颜色。

有什么想法吗?

【问题讨论】:

标签: ios swift sprite-kit


【解决方案1】:

这是一个工作示例,只需更改颜色:

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

这将无休止地循环颜色,因此您更改循环机制,该方法将不断调用自身,直到您发出删除所有动画的命令。

【讨论】:

  • 你可以在任何你想使用的地方使用这段代码,但是对于这个例子,我把它放在一个视图控制器的 viewDidLoad 中
【解决方案2】:

第一:

创建一个视图(或一个盒子),设置它填满屏幕;让我们称之为背景
将其颜色设置为#e0f1f8(浅蓝色)

下一步:这段代码应该可以开始了 -

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

希望这会有所帮助。祝你好运!

功劳归于:

Source for my Answer

【讨论】:

  • 我认为你不能像这样使用十六进制来分配颜色。通常是带有 rgb 属性的 UIColor
  • 哦。哎呀:-/感谢那里的指针。我同时做 web 和 IOS 的工作,但最近它更加专注于 web,所以我在错误的方向上有点人手不足。我会对此进行编辑。谢谢。