Skip to content

Instantly share code, notes, and snippets.

@gromwel
Created March 22, 2021 15:00
Show Gist options
  • Save gromwel/2375c6add0cc1418f5037eb6e00746fe to your computer and use it in GitHub Desktop.
Save gromwel/2375c6add0cc1418f5037eb6e00746fe to your computer and use it in GitHub Desktop.
Contrast foreground text color
import UIKit
extension UIColor {
static func contrastTextColor(with background: UIColor) -> UIColor {
let darkText = UIColor.dark
let lightText = UIColor.white
return background.contrastRatio(with: darkText) > background.contrastRatio(with: lightText) ? darkText : lightText
}
}
fileprivate extension UIColor {
// MARK: Контраст по WCAG 2.0
func contrastRatio(with color: UIColor) -> CGFloat {
return UIColor.contrastRatio(between: self, and: color)
}
private static func contrastRatio(between color1: UIColor, and color2: UIColor) -> CGFloat {
// Методика расчета: https://www.w3.org/TR/WCAG20-TECHS/G18.html#G18-tests
// Рекомендуется придерживаться контраста > 4.5
let luminance1 = color1.luminance()
let luminance2 = color2.luminance()
let luminanceDarker = min(luminance1, luminance2)
let luminanceLighter = max(luminance1, luminance2)
return (luminanceLighter + 0.05) / (luminanceDarker + 0.05)
}
private func luminance() -> CGFloat {
let ciColor = CIColor(color: self)
let adjust = { (component: CGFloat) -> CGFloat in
(component < 0.03928) ? (component / 12.92) : pow((component + 0.055) / 1.055, 2.4)
}
return 0.2126 * adjust(ciColor.red) + 0.7152 * adjust(ciColor.green) + 0.0722 * adjust(ciColor.blue)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment