Created
January 19, 2021 23:49
-
-
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:)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
@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!)
👍 😸
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This was just what I was looking for, thanks for posting it!