Created
May 29, 2019 01:08
-
-
Save adamgraham/b1bd57d6611ca623fbf0f3a058688ea5 to your computer and use it in GitHub Desktop.
An extension of the iOS class UIColor to derive web safe colors.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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