首页 > 解决方案 > 如何在 UIColor 中获得随机的暖色/冷色?

问题描述

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

根据这篇文章,我们可以假设:

if (B > R) { 
    color = cool
} else { 
    color = warm
}

如何修改我的随机扩展以选择随机暖色或随机冷色。

有什么建议吗?

标签: iosswiftuikituicolor

解决方案


如果你首先生成你的数字,你可以blue在你的计算中使用这个值red......

extension UIColor {
    static var warm: UIColor {
        let red: CGFloat = .random(in: 0...1)
        let blue: CGFloat = .random(in: 0..<red)
        return UIColor(red: red, green: .random(in: 0...1), blue: blue, alpha: 1)
    }

    static var cool: UIColor {
        let blue: CGFloat = .random(in: 0...1)
        let red: CGFloat = .random(in: 0..<blue)
        return UIColor(red: red, green: .random(in: 0...1), blue: blue, alpha: 1)
    }
}

这将满足您对冷是红色小于蓝色和暖色是蓝色小于红色的要求。


推荐阅读