Last active
September 16, 2019 06:27
-
-
Save dagronf/b9694866a364ceaf823ebad73672ae4c to your computer and use it in GitHub Desktop.
Get a contrasting UIColor for a background UIColor that could be used for text (for eg.)
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
import UIKit | |
extension UIColor { | |
private struct ColorComponents { | |
var r: CGFloat = 0.0 | |
var g: CGFloat = 0.0 | |
var b: CGFloat = 0.0 | |
var a: CGFloat = 0.0 | |
} | |
private func components() -> ColorComponents { | |
var result = ColorComponents() | |
self.getRed(&result.r, green: &result.g, blue: &result.b, alpha: &result.a) | |
return result | |
} | |
func contrastingTextColor() -> UIColor { | |
if self == UIColor.clear { | |
return .black | |
} | |
let rgbColor = self.components() | |
// Counting the perceptive luminance - human eye favors green color... | |
let avgGray: CGFloat = 1 - (0.299 * rgbColor.r + 0.587 * rgbColor.g + 0.114 * rgbColor.b) | |
return avgGray > 0.5 ? .white : .black | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment