Last active
June 2, 2019 00:22
-
-
Save adamgraham/fa64d7cd03aa438d81c65f9dc965ae2c to your computer and use it in GitHub Desktop.
An extension of the iOS class UIColor to provide conversion to and from CIE xyY colors.
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
/// An extension to provide conversion to and from CIE xyY colors. | |
extension UIColor { | |
/// The CIE xyY components of a color - luminance (Y) and chromaticity (x,y). | |
struct CIExyY: Hashable { | |
/// The x-axis chromaticity coordinate of the color, in the range [0, 1]. | |
var x: CGFloat | |
/// The y-axis chromaticity coordinate of the color, in the range [0, 1]. | |
var y: CGFloat | |
/// The luminance component of the color, in the range [0, 100]. | |
var Y: CGFloat | |
} | |
/// The CIE xyY components of the color. | |
var xyY: CIExyY { | |
let XYZ = self.XYZ | |
let sum = XYZ.X + XYZ.Y + XYZ.Z | |
guard sum != 0.0 else { | |
return CIExyY(x: 0.0, y: 0.0, Y: XYZ.Y) | |
} | |
let x = XYZ.X / sum | |
let y = XYZ.Y / sum | |
return CIExyY(x: x, y: y, Y: XYZ.Y) | |
} | |
/// Initializes a color from CIE xyY components. | |
/// - parameter xyY: The components used to initialize the color. | |
/// - parameter alpha: The alpha value of the color. | |
convenience init(_ xyY: CIExyY, alpha: CGFloat = 1.0) { | |
guard xyY.y != 0.0 else { | |
self.init(CIEXYZ(X: 0.0, Y: xyY.Y, Z: 0.0), alpha: alpha) | |
return | |
} | |
let X = (xyY.x * xyY.Y) / xyY.y | |
let Y = xyY.Y | |
let Z = ((1.0 - xyY.x - xyY.y) * xyY.Y) / xyY.y | |
self.init(CIEXYZ(X: X, Y: Y, Z: Z), alpha: alpha) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This requires the
CIEXYZ
extension declared at https://gist.github.com/adamgraham/677c0c41901f3eafb441951de9bc914c