1

I would like to randomly choose 2 colors. But it has to be a random cold color and a random warm color.

I am using this extension to take a random color :

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

According to this post, we can assume that :

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

How can I modify my random extension to be able to select random warm color or random cold color.

Any advices ?

Funnycuni
  • 369
  • 1
  • 15

2 Answers2

6

If you generate your numbers first you can use the value of blue in your calculation of red something like this...

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

This will satisfy your requirement for cool is red less than blue and warm is blue less than red.

Fogmeister
  • 76,236
  • 42
  • 207
  • 306
  • 1
    Your method could produce warm colors with no red, cool colors with no blue, or either kind of color where the red and blue components are too close for you to see the difference. See my answer (with a nod to yours, since it's a slight variation) which forces warm colors to have a significant red component, cool colors to have a significant blue component, and both to have less of the "other" color. – Duncan C Jan 20 '20 at 23:01
2

Fogmeister's answer meets the technical requirement, but it has some problems. For a warm color, if red is low enough, you won't see it. The blue component of a warm color may be so close to the red that there's no visible difference, etc.

I'd suggest this instead:

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)
    }
}
Duncan C
  • 128,072
  • 22
  • 173
  • 272