Skip to content

Instantly share code, notes, and snippets.

@adamgraham
Created May 29, 2019 01:08
Show Gist options
  • Save adamgraham/b1bd57d6611ca623fbf0f3a058688ea5 to your computer and use it in GitHub Desktop.
Save adamgraham/b1bd57d6611ca623fbf0f3a058688ea5 to your computer and use it in GitHub Desktop.
An extension of the iOS class UIColor to derive web safe colors.
/// An extension to derive web safe colors.
extension UIColor {
/// The nearest web safe color to the current color. All web safe colors have RGB
/// component values of 0, 51, 102, 153, 204, or 255 (20% intervals).
var webSafe: UIColor {
var (r, g, b, a) = (CGFloat(), CGFloat(), CGFloat(), CGFloat())
getRed(&r, green: &g, blue: &b, alpha: &a)
let clusters: [CGFloat] = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0]
func quantize(_ component: CGFloat) -> CGFloat {
return clusters.min(by: { abs($0 - component) < abs($1 - component) })!
}
r = quantize(r)
g = quantize(g)
b = quantize(b)
return UIColor(red: r, green: g, blue: b, alpha: a)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment