Swift在Colorwheel上生成随机颜色

时间:2016-10-13 19:29:39

标签: swift xcode

我正在使用SwiftHSVColorPicker框架并需要在色轮上生成随机颜色。我目前的工作方式有效,但亮度偏离。这是我的代码

func generateRandomColor() -> UIColor {
    let lowerx : UInt32 = UInt32(0.0)
    let upperx : UInt32 = 707
    let randomNumberx = arc4random_uniform(upperx - lowerx) + lowerx
    let lowery : UInt32 = UInt32(0.0)
    let uppery : UInt32 = 707
    let randomNumbery = arc4random_uniform(upperx - lowerx) + lowerx
    let c = Colorwheel.colorWheel.hueSaturationAtPoint(CGPoint(x: Double(randomNumberx), y: Double(randomNumbery)))
    let brightness = 1.0
    return UIColor(hue: c.hue, saturation: c.saturation, brightness: CGFloat(brightness), alpha: 1.0)
}

1 个答案:

答案 0 :(得分:1)

为什么不使用像

这样的东西
func getRandomColor() -> UIColor{

    let randomRed:CGFloat = CGFloat(arc4random()) / CGFloat(UInt32.max)
    let randomGreen:CGFloat = CGFloat(arc4random()) / CGFloat(UInt32.max)
    let randomBlue:CGFloat = CGFloat(arc4random()) / CGFloat(UInt32.max)

    return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0)

}

修改

试试这个,在此hue中,brightness也在那里

func generateRandomColor() -> UIColor {
  let hue : CGFloat = CGFloat(arc4random() % 256) / 256 // use 256 to get full range from 0.0 to 1.0
  let saturation : CGFloat = CGFloat(arc4random() % 128) / 256 + 0.5 // from 0.5 to 1.0 to stay away from white
  let brightness : CGFloat = CGFloat(arc4random() % 128) / 256 + 0.5 // from 0.5 to 1.0 to stay away from black

  return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1)
}

SwiftHSVColorPicker 结果

enter image description here