Skip to content

Instantly share code, notes, and snippets.

@WorldDownTown
Last active December 28, 2023 06:01
Show Gist options
  • Save WorldDownTown/06ffae6f774fe3b632f6fb2c9343d7f0 to your computer and use it in GitHub Desktop.
Save WorldDownTown/06ffae6f774fe3b632f6fb2c9343d7f0 to your computer and use it in GitHub Desktop.
Get contrast ratio between two UIColors
// https://www.w3.org/TR/WCAG20/
// Contrast ratio
// Relative luminance
import UIKit
extension UIColor {
convenience init(hex: UInt, alpha: CGFloat = 1) {
self.init(red: CGFloat((hex & 0xff0000) >> 16) / 255,
green: CGFloat((hex & 0x00ff00) >> 8) / 255,
blue: CGFloat(hex & 0x0000ff) / 255,
alpha: alpha)
}
}
private struct RGB {
let red, green, blue: CGFloat
}
private extension RGB {
init(color: UIColor) {
let components: [CGFloat] = color.cgColor.components!
self.init(red: components[0], green: components[1], blue: components[2])
}
}
struct Luminance: RawRepresentable {
let rawValue: CGFloat
}
extension Luminance {
init(color: UIColor) {
self.init(rgb: RGB(color: color))
}
private init(rgb: RGB) {
func relativeLuminance(from value: CGFloat) -> CGFloat {
value <= 0.03928 ? value / 12.92 : pow((value + 0.055) / 1.055, 2.4)
}
let red: CGFloat = relativeLuminance(from: rgb.red)
let green: CGFloat = relativeLuminance(from: rgb.green)
let blue: CGFloat = relativeLuminance(from: rgb.blue)
rawValue = red * 0.2126 + green * 0.7152 + blue * 0.0722
}
}
struct ContrastRatio: RawRepresentable {
let rawValue: CGFloat
}
extension ContrastRatio {
init(light: UIColor, dark: UIColor) {
rawValue = (Luminance(color: light).rawValue + 0.05) / (Luminance(color: dark).rawValue + 0.05)
}
}
let lightOrange: UIColor = .init(hex: 0xf8a23b)
let darkOrange: UIColor = .init(hex: 0xf18828)
ContrastRatio(light: lightOrange, dark: darkOrange).rawValue
// 1.2327559224150646
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment