Skip to content

Instantly share code, notes, and snippets.

@nicklockwood
Created January 19, 2021 23:49
Show Gist options
  • 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
}
Copy link

ghost commented May 4, 2024

This was just what I was looking for, thanks for posting it!

@nicklockwood
Copy link
Author

@mneuburg-livefront you're very welcome!

(You aren't by any chance the same Matt Neuburg that authored multiple iOS development books are you? If so it was one of your books that first got me into iOS development ~15 years ago, so I'm doubly happy to return the favor!)

Copy link

ghost commented May 4, 2024

👍 😸

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