Skip to content

Instantly share code, notes, and snippets.

@benjaminsnorris
Created May 9, 2016 21:56
Show Gist options
  • Save benjaminsnorris/0e7f89670edbe709a3a0ea56cff61714 to your computer and use it in GitHub Desktop.
Save benjaminsnorris/0e7f89670edbe709a3a0ea56cff61714 to your computer and use it in GitHub Desktop.
Get UIColor from hex value
// MARK: - HEX init
// From Tim Shadel
enum UIColorInputError: ErrorType {
case UnableToScanHexValue
}
extension UIColor {
convenience init(hex: Int, alpha: CGFloat = 1.0) {
let red = CGFloat((hex >> 16) & 0xFF)/255.0
let green = CGFloat((hex >> 8) & 0xFF)/255.0
let blue = CGFloat((hex) & 0xFF)/255.0
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
convenience init(hexString: String, alpha: CGFloat = 1.0) throws {
var hexValue: UInt32 = 0
guard NSScanner(string: hexString).scanHexInt(&hexValue) else { throw UIColorInputError.UnableToScanHexValue }
self.init(hex: Int(hexValue), alpha: alpha)
}
var hexString: String {
var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
if !self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) {
self.getWhite(&red, alpha: &alpha)
green = red
blue = red
}
red = CGFloat(roundf(Float(red) * 255.0))
green = CGFloat(roundf(Float(green) * 255.0))
blue = CGFloat(roundf(Float(blue) * 255.0))
alpha = CGFloat(roundf(Float(alpha) * 255.0))
// Ignore alpha for now
let hex: UInt = (UInt(red) << 16) | (UInt(green) << 8) | (UInt(blue))
return String(format: "%06x", hex)
}
}
extension UIColor: ValueType {
public static func value(object: Any) throws -> UIColor {
guard let colorString = object as? String, objectValue = try? UIColor(hexString: colorString) else {
throw Error.TypeMismatch(expected: self, actual: object.dynamicType)
}
return objectValue
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment