Skip to content

Commit 5daf000

Browse files
Add helper method for calculating contrast ratio
Based on code from https://gist.github.com/ngquerol/23d6d5ebd051e18682badafa37e48442. The calculated contrast ratio can be passed to the WCAGLevel constructor to get the final contrast level.
1 parent 6fbaa1a commit 5daf000

1 file changed

Lines changed: 27 additions & 0 deletions

File tree

Pixel Picker/NSColor.swift

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,4 +50,31 @@ extension NSColor {
5050
let L = 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2];
5151
return L > 0.197 ? NSColor.black : NSColor.white
5252
}
53+
54+
// Calculates the contrast ratio of this color and another one, according to the W3C "Web Content Accessibility Guidelines (WCAG) 2.0" Recommendation (https://www.w3.org/TR/WCAG20/).
55+
// Adopted from: https://gist.github.com/ngquerol/23d6d5ebd051e18682badafa37e48442
56+
public func contrastRatio(to color: NSColor) -> CGFloat {
57+
let luminance1 = relativeLuminance,
58+
luminance2 = color.relativeLuminance
59+
60+
if luminance1 < luminance2 {
61+
return (luminance2 + 0.05) / (luminance1 + 0.05)
62+
} else {
63+
return (luminance1 + 0.05) / (luminance2 + 0.05)
64+
}
65+
}
66+
67+
// Calculates the relative brightness of a color, according to the W3C "Web Content Accessibility Guidelines (WCAG) 2.0" Recommendation (https://www.w3.org/TR/WCAG20/).
68+
// Adopted from: https://gist.github.com/ngquerol/23d6d5ebd051e18682badafa37e48442
69+
public var relativeLuminance: CGFloat {
70+
let f = { (component: CGFloat) -> CGFloat in
71+
return component <= 0.03928 ? component / 12.92 : pow((component + 0.055) / 1.055, 2.4)
72+
}
73+
74+
let red = f(redComponent)
75+
let green = f(greenComponent)
76+
let blue = f(blueComponent)
77+
78+
return red * 0.2126 + green * 0.7152 + blue * 0.0722
79+
}
5380
}

0 commit comments

Comments
 (0)