Created
January 18, 2020 20:58
-
-
Save eamonnalphin/9e0b48b9d6e347182f268a3271659e53 to your computer and use it in GitHub Desktop.
Some useful UIColor extensions in swift
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
//Gets a random UIColor | |
extension UIColor { | |
static func random() -> UIColor { | |
return UIColor(red: .random(), | |
green: .random(), | |
blue: .random(), | |
alpha: 1.0) | |
} | |
} | |
//Gets a random UIColor that's light enough to use with black text. | |
extension UIColor { | |
static func randomLightColor() -> UIColor { | |
var thisColor = UIColor.random() | |
while(!(thisColor.isLight() ?? true)){ | |
thisColor = UIColor.random() | |
} | |
return thisColor | |
} | |
} | |
//gets a random CGFloat | |
extension CGFloat { | |
static func random() -> CGFloat { | |
return CGFloat(arc4random()) / CGFloat(UInt32.max) | |
} | |
} | |
//returns true if a UIColor is "light" | |
extension UIColor { | |
// Check if the color is light or dark, as defined by the injected lightness threshold. | |
// Some people report that 0.7 is best. I suggest to find out for yourself. | |
// A nil value is returned if the lightness couldn't be determined. | |
func isLight(threshold: Float = 0.6) -> Bool? { | |
let originalCGColor = self.cgColor | |
// Now we need to convert it to the RGB colorspace. UIColor.white / UIColor.black are greyscale and not RGB. | |
// If you don't do this then you will crash when accessing components index 2 below when evaluating greyscale colors. | |
let RGBCGColor = originalCGColor.converted(to: CGColorSpaceCreateDeviceRGB(), intent: .defaultIntent, options: nil) | |
guard let components = RGBCGColor?.components else { | |
return nil | |
} | |
guard components.count >= 3 else { | |
return nil | |
} | |
let brightness = Float(((components[0] * 299) + (components[1] * 587) + (components[2] * 114)) / 1000) | |
return (brightness > threshold) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment