Skip to content

Instantly share code, notes, and snippets.

@joaomvfsantos
Created May 29, 2023 17:21
Show Gist options
  • Save joaomvfsantos/799c36bc30e88ac0edf16abd16054eb9 to your computer and use it in GitHub Desktop.
Save joaomvfsantos/799c36bc30e88ac0edf16abd16054eb9 to your computer and use it in GitHub Desktop.
Swift UIColor extension, that adds a contrast ratio function between two colors.
//
// ContrastRatioSwift.swift
// Contrast Ratio Swift
//
// Created by João Santos on 25/05/2023.
// Copyright © 2023 João Santos. All rights reserved.
//
import UIKit
extension UIColor {
var luminance: CGFloat {
let RED: CGFloat = 0.2126
let GREEN: CGFloat = 0.7152
let BLUE: CGFloat = 0.0722
let GAMMA: CGFloat = 2.4
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
self.getRed(&r, green: &g, blue: &b, alpha: nil)
let a = [r, g, b]
.map({ v in
return v <= 0.03928 ? v / 12.92 : pow((v + 0.055) / 1.055, GAMMA)
})
return a[0] * RED + a[1] * GREEN + a[2] * BLUE
}
func contrastTo(color: UIColor) -> CGFloat {
let lum1 = self.luminance
let lum2 = color.luminance
let brightest = max(lum1, lum2)
let darkest = min(lum1, lum2)
return (brightest + 0.05) / (darkest + 0.05)
}
func hasEnoughContrast(toColor color: UIColor, forTextSize size: CGFloat = 16, weight: UIFont.Weight = .regular) -> Bool {
let contrast = self.contrastTo(color: color)
switch weight {
case .medium, .semibold, .bold, .heavy, .black:
return size >= 14 && contrast >= 3
default:
return contrast >= 4.5
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment