Skip to content

Instantly share code, notes, and snippets.

@Tricertops
Last active March 31, 2017 14:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tricertops/c2485f4039b3bdaeaf08932be95e6845 to your computer and use it in GitHub Desktop.
Save Tricertops/c2485f4039b3bdaeaf08932be95e6845 to your computer and use it in GitHub Desktop.
Construct UIColor using HSB components in Display P3 color space.
extension UIColor {
convenience init(displayP3Hue hue: CGFloat, saturation: CGFloat, brightness: CGFloat, alpha: CGFloat = 1) {
/// HSB to RGB conversion doesn’t depend on color space, so we can use default UIColor space.
let converter = UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1)
var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0
converter.getRed(&red, green: &green, blue: &blue, alpha: nil)
self.init(displayP3Red: red, green: green, blue: blue, alpha: alpha)
}
}
UIColor(displayP3Hue: 0.2, saturation: 1, brightness: 1) // r 0,745 g 1,007 b -0,333 a 1,0
@kartickvad
Copy link

Thanks for this, Tricertops. I'm trying to create a desaturated version of a given color in the P3 color space, like this:

extension UIColor {
  static let noticeablePink = UIColor(displayP3Red: 1, green: 0, blue: 0.8, alpha: 1)

  // Returns a desaturated version of the receiver. If the factor is 2, the saturation of the returned
  // color will be half that of the receiver.
  func desaturated(_ factor: CGFloat) -> UIColor {
    var hue: CGFloat = 0
    var saturation: CGFloat = 0
    var brightness: CGFloat = 0
    var alpha: CGFloat = 0

    getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)

    saturation /= factor

    return UIColor(displayP3Hue: hue, saturation: saturation, brightness: brightness)
  }
}

This seems wrong, because when I invoke it with argument 1:

UIColor.noticeablePink.desaturated(1)

I get:

UIDisplayP3ColorSpace 1 0 0.822868 1

Notice that the blue is 0.822, not 0.8. Any idea why?

@kartickvad
Copy link

I forgot to say: I also get a warning saying:

[Graphics] UIColor created with component values far outside the expected range.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment