Last active
January 6, 2017 03:00
-
-
Save vhart/f7d07a56c8f088d40014626485656a0a to your computer and use it in GitHub Desktop.
UIColor from hex
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
extension UIColor { | |
convenience init? (fromHex hex: String) { | |
let hexPattern = try! NSRegularExpression(pattern: "^[0-9a-fA-F]{6}$", | |
options: [.anchorsMatchLines]) | |
let range = NSRange(location: 0, length: hex.characters.count) | |
guard hexPattern.matches(in: hex, | |
options: [], | |
range: range).count == 1 | |
else { return nil } | |
let positionR = hex.index(hex.startIndex, offsetBy: 2) | |
let positionG = hex.index(hex.startIndex, offsetBy: 4) | |
guard let r = Double("0x" + hex.substring(to: positionR)), | |
let g = Double("0x" + hex.substring(with: positionR..<positionG)), | |
let b = Double("0x" + hex.substring(from: positionG)) else { return nil } | |
self.init(red: CGFloat(r / 255), | |
green: CGFloat(g / 255), | |
blue: CGFloat(b / 255), | |
alpha: 1) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment