I\'m looking for a concise way to compute the color contrast ratio between two UIColor instances in Swift. I\'ve found examples that are close but are overly compli
If building for WatchOS where CoreImage is not available or for whatever reason you do not want to rely on CoreImage and therefore CIColor is unavailable, replace @Mobile Dan's luminance function with:
private func luminance() -> CGFloat {
// https://www.w3.org/TR/WCAG20-TECHS/G18.html#G18-tests
func adjust(colorComponent: CGFloat) -> CGFloat {
return (colorComponent < 0.03928) ? (colorComponent / 12.92) : pow((colorComponent + 0.055) / 1.055, 2.4)
}
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
getRed(&red, green: &green, blue: &blue, alpha: &alpha)
return 0.2126 * adjust(colorComponent: red)
+ 0.7152 * adjust(colorComponent: green)
+ 0.0722 * adjust(colorComponent: blue)
}