Last active
August 24, 2018 15:00
-
-
Save Gatada/82332952601ece9fcfeb5fb36fbd391b to your computer and use it in GitHub Desktop.
A extension for UIColor that creates a UIColor from a hex code.
This file contains hidden or 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 | |
public extension UIColor { | |
/// Initialize a color from a hex value. Optionally include an alpha value (default is 1). | |
/// | |
/// - Parameters: | |
/// - hex: The integer that will be resolved to the red, green and blue component. | |
/// - alpha: The alpha value of the color. | |
public convenience init?(hex: UInt, alpha: CGFloat = 1) { | |
guard hex <= 0xFFFFFF else { | |
// Value is out of range; an invalid color | |
return nil | |
} | |
let red = CGFloat((hex & 0xFF0000) >> 16)/255 | |
let green = CGFloat((hex & 0x00FF00) >> 8)/255 | |
let blue = CGFloat(hex & 0x0000FF)/255 | |
self.init(red: red, green: green, blue: blue, alpha: alpha) | |
} | |
/// Initalize a UIColor from a hex string that optionally includes an alpha component. | |
/// The hex string must be prefixed with #. | |
/// | |
/// - Parameter hex: The hex value as a string representing RGB or RGBA, prefixed with #. | |
public convenience init?(hex: String) { | |
let includesAlphaComponent = (hex.count == 9) | |
guard hex.hasPrefix("#"), includesAlphaComponent || hex.count == 7 else { | |
// Invalid hex format | |
return nil | |
} | |
let start = hex.index(hex.startIndex, offsetBy: 1) | |
let hexColor = String(hex[start...]) | |
let scanner = Scanner(string: hexColor) | |
var hexNumber: UInt64 = 0 | |
guard scanner.scanHexInt64(&hexNumber) else { | |
// Invalid hex number | |
return nil | |
} | |
let alpha = includesAlphaComponent ? CGFloat(hexNumber & 0xFF) / 255 : 1 | |
let hex = includesAlphaComponent ? UInt(hexNumber >> 8) : UInt(hexNumber) | |
self.init(hex: hex, alpha: alpha) | |
} | |
/// Returns a color with brightness set to be 50% (round robin) off from the source color. | |
/// In other words, the resulting color with be perfectly harmonious and easily visible together with the source color. | |
/// | |
/// - Returns: an harmonious color with inverted brightness. | |
func contrastingColor() -> UIColor { | |
var hue: CGFloat = 1 | |
var saturation: CGFloat = 1 | |
var brightness: CGFloat = 1 | |
var alpha: CGFloat = 1 | |
assert(getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha), "Color is not UIColor.getHue compatible.") | |
return UIColor(hue: hue, saturation: saturation, brightness: ((brightness + 0.5) % 1), alpha: alpha) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment