Last active
August 12, 2023 01:16
-
-
Save laevandus/b9d8cdc8fc76fb8541eb5ed946a32bd2 to your computer and use it in GitHub Desktop.
Calculation color contrast ratio useful for making apps more accessible and easy to read.
This file contains 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 | |
/* | |
Contrast ratio is calculated using the proceedure here: | |
https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-procedure | |
*/ | |
public extension UIColor { | |
/// Relative luminance of the color. | |
var relativeLuminance: CGFloat { | |
var red: CGFloat = 0 | |
var green: CGFloat = 0 | |
var blue: CGFloat = 0 | |
guard getRed(&red, green: &green, blue: &blue, alpha: nil) else { return 1.0 } | |
let convert: (CGFloat) -> CGFloat = { component in | |
guard component > 0.03928 else { return component / 12.92 } | |
return pow(((component + 0.055) / 1.055), 2.4) | |
} | |
return 0.2126 * convert(red) + 0.7152 * convert(green) + 0.0722 * convert(blue) | |
} | |
/// Returns contrast ratio with other color. | |
/// - Parameter otherColor: UIColor in RGB color space. | |
/// - Returns: Contrast ratio of two colors. | |
func contrastRatio(_ otherColor: UIColor) -> CGFloat { | |
let luminance1 = relativeLuminance | |
let luminance2 = otherColor.relativeLuminance | |
return (min(luminance1, luminance2) + 0.05) / (max(luminance1, luminance2) + 0.05) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment