ios - 如何在UIColor中获得随机的暖色/冷色?

标签 ios swift uikit 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)
    }
}

根据这个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/

相关文章:

IOS Twilio IP 消息系统初始集成步骤

iOS UIButton - UIButton setUserInteractionEnabled 和 setEnabled 之间的区别

ios - 如何在 AVQueuePlayer 或 AVMutableComposition 中播放多个视频而没有任何间隙或卡住?

ios - iPA 构建失败,并出现异常 - 为 QA 测试/AdHod 准备构建时出现 NonZeroExcitException

ios - IQKeyboardManager 没有成员 sharedManager

swift - 根据 Swift 3 中的日期和文本设置分隔符(UIView)的颜色

swift - 'NSUnknownKeyException',原因 : '[<Users 0x78eb5bf0> valueForUndefinedKey:]: the entity Users is not key value coding-compliant for the key "James". '

ios - 如何在 iOS 的小键盘上添加一个 'Done' 按钮

objective-c - 如何禁用 UIButton 和禁用 touchEvent 响应器?

ios - IBOutletCollection - 如何对数组应用排序?