Skip to content

Instantly share code, notes, and snippets.

@nicklockwood
Created January 19, 2021 23:49
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicklockwood/96aea92b8cf3997cd4a0e87e1edde570 to your computer and use it in GitHub Desktop.
Save nicklockwood/96aea92b8cf3997cd4a0e87e1edde570 to your computer and use it in GitHub Desktop.
Getting the Display P3 values back out of a UIColor created with init(displayP3Red:green:blue:alpha:)
import UIKit
// Create color using P3 color space
let linearColor = UIColor(displayP3Red: 1, green: 0.5, blue: 0.2, alpha: 1)
do {
var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
linearColor.getRed(&r, green: &g, blue: &b, alpha: &a)
print(r, g, b, a) // 1.07, 0.46, 0.0, 1.0 - not the expected values
}
// Convert to P3
let p3Color: UIColor = {
guard let colorSpace = CGColorSpace(name: CGColorSpace.displayP3),
let cgColor = linearColor.cgColor.converted(
to: colorSpace,
intent: .defaultIntent,
options: nil
),
let rgba = cgColor.components,
rgba.count == 4
else {
return linearColor
}
// FWIW, I could actually just use these component values directly instead
// of converting back to a UIColor to extract them again
return UIColor(red: rgba[0], green: rgba[1], blue: rgba[2], alpha: rgba[3])
}()
do {
var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
p3Color.getRed(&r, green: &g, blue: &b, alpha: &a)
print(r, g, b, a) // 1.0, 0.5, 0.2, 1.0 - matches the input values
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment