我想randomly
选择2种颜色。但是它必须是随机的cold
颜色和随机的warm
颜色。
我正在使用此extension
采取随机颜色:
extension UIColor {
static var random: UIColor {
return UIColor(red: .random(in: 0...1),
green: .random(in: 0...1),
blue: .random(in: 0...1),
alpha: 1.0)
}
}
根据这个post,我们可以假设:
if (B > R) {
color = cool
} else {
color = warm
}
如何修改我的随机扩展名,以便能够选择随机的暖色或随机的冷色。
有什么建议吗?
最佳答案
Fogmeister的答案符合技术要求,但存在一些问题。对于暖色,如果红色足够低,则看不到它。暖色的蓝色成分可能与红色非常接近,以至于没有可见的差异等。
我建议这样做:
extension UIColor {
static var warm: UIColor {
let red: CGFloat = .random(in: 0.6...1) /Force red to be at least 0.6
let blue: CGFloat = .random(in: 0..<0.5) //Force blue to be smaller
return UIColor(red: red, green: .random(in: 0...1), blue: blue, alpha: 1)
}
static var cool: UIColor {
let blue: CGFloat = .random(in: 0.6..<1.0) //Force blue to be > 0.6
let red: CGFloat = .random(in: 0...0.5) //Force red to be smaller
return UIColor(red: red, green: .random(in: 0...1), blue: blue, alpha: 1)
}
}
关于ios - 如何在UIColor中获得随机的暖色/冷色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59826377/