Get a color's CIE XYZ values with toXYZ(), the space the other color spaces are defined from. It takes nothing and returns an XYZColor, whose y is the color's relative luminance:
Color(hex: "#00B386").toXYZ() // XYZColor(x: 0.204, y: 0.340, z: 0.280)Relative luminance#
y runs from 0 for black to 1 for white, and it's the number WCAG contrast is built on. To check a pair of colors, use contrastRatio(to:method:), which does the math for you.
Converting onward#
XYZ is a step between spaces: from an XYZColor you can go to toRGB(), toLAB() and toLCH(). It has no toColor(), so go through RGB or LCH to draw it, as in xyz.toLCH().toColor().
How it behaves#
The white point is D65. Inside sRGB, x runs from 0 to 0.95, y from 0 to 1 and z from 0 to 1.09; conversions pass through extended sRGB without clipping, so Display P3 colors reach further. A token gives its light-mode value on iOS 17, macOS 14 and later. lerp(_:t:) mixes two XYZColor values in a straight line.
API#
public extension Color {
func toXYZ() -> XYZColor
}
public struct XYZColor: Hashable, Sendable {
public let x: CGFloat // 0 to 0.95 inside sRGB
public let y: CGFloat // 0 to 1, relative luminance
public let z: CGFloat // 0 to 1.09 inside sRGB
public let alpha: CGFloat // 0 to 1
public init(x: CGFloat, y: CGFloat, z: CGFloat, alpha: CGFloat)
public func lerp(_ other: XYZColor, t: CGFloat) -> XYZColor
public func toRGB() -> RGBColor
public func toLAB() -> LABColor
public func toLCH() -> LCHColor
}toXYZ() takes no parameters.
Sources#
- Color+ColorSpaces.swift, which defines
toXYZ()onColor. - The XYZ folder, which defines
XYZColor. - W3C, Web Content Accessibility Guidelines (WCAG) 2.2, which defines relative luminance.
See also
- .contrastRatio(to:method:) Check WCAG 2 and APCA contrast in Swift, and keep your color pairs passing with a unit test.
- .toLAB() Change a color's lightness alone in CIELab, the lightness that decides contrast.
- .toRGB() Read a color's red, green and blue channels, even past sRGB, to hand to other graphics code.
- Glossary of color terms Look up any color term on this site in plain words, from stop and token to chroma and gamut.