Swift随机颜色生成器

时间:2015-08-13 22:08:24

标签: swift double uicolor cgfloat type-conversion

我正在制作一个游戏,其中有一个正方形网格,一个是不同的颜色(所有颜色都是绿松石色)。我正在使用一个函数来生成两种不同的随机颜色

func generateColors() -> (main: UIColor, diff: UIColor) {

    let redMain: CGFloat = CGFloat(arc4random(104.0))
    let greenMain: CGFloat = redMain + 105
    let blueMain: CGFloat = redMain + 83

    let redColorMain: CGFloat = redMain / 255.0
    let greenColorMain: CGFloat = greenMain / 255.0
    let blueColorMain: CGFLoat = blueMain / 255.0
    let main = UIColor(red: redColorMain, green: greenColorMain, blue: blueColorMain, alpha: 0.8)

    let redDiff: CGFloat = CGFloat(arc4random(104.0))
    let greenDiff: CGFloat = redDiff + 105
    let blueDiff: CGFloat = redDiff + 83

    let redColorDiff: CGFloat = redDiff / 255.0
    let greenColorDiff: CGFloat = greenDiff / 255.0
    let blueColorDiff: CGFloat = blueDiff / 255
    let diff = UIColor(red: redColorDiff, green: greenColorDiff, blue: blueColorDiff, alpha: 0.8)

    return (main, diff)
}

但是,我一直收到错误消息“无法使用参数类型'Double'调用arc4random”。为什么会这样说,你知道怎么解决吗?谢谢!

1 个答案:

答案 0 :(得分:1)

试试这样:

func generateColors() -> (main: UIColor, diff: UIColor) {

    let redMain: CGFloat = CGFloat(arc4random_uniform(104))
    let greenMain: CGFloat = redMain + 105.0
    let blueMain: CGFloat = redMain + 83.0

    let redColorMain: CGFloat = redMain / 255.0
    let greenColorMain: CGFloat = greenMain / 255.0
    let blueColorMain: CGFloat = blueMain / 255.0
    let main = UIColor(red: redColorMain, green: greenColorMain, blue: blueColorMain, alpha: 0.8)

    let redDiff: CGFloat = CGFloat(arc4random_uniform(104))
    let greenDiff: CGFloat = redDiff + 105.0
    let blueDiff: CGFloat = redDiff + 83.0

    let redColorDiff: CGFloat = redDiff / 255.0
    let greenColorDiff: CGFloat = greenDiff / 255.0
    let blueColorDiff: CGFloat = blueDiff / 255.0
    let diff = UIColor(red: redColorDiff, green: greenColorDiff, blue: blueColorDiff, alpha: 0.8)

    return (main, diff)
}