Created
February 2, 2019 22:42
-
-
Save giftbott/d2ceba540dab735f8ce6433bb2cc33db to your computer and use it in GitHub Desktop.
hexColor Extension
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 String { | |
| func hexToColor() -> UIColor { | |
| let hexString = self.trimmingCharacters(in: .whitespacesAndNewlines) | |
| let scanner = Scanner(string: hexString) | |
| if hexString.hasPrefix("#") { | |
| scanner.scanLocation = 1 | |
| } | |
| let mask: UInt64 = 0xFF | |
| var color: UInt64 = 0 | |
| scanner.scanHexInt64(&color) | |
| let red = (color >> 16) & mask | |
| let green = (color >> 8) & mask | |
| let blue = color & mask | |
| return UIColor(red: CGFloat(red) / 255.0, | |
| green: CGFloat(green) / 255.0, | |
| blue: CGFloat(blue) / 255.0, | |
| alpha: 1.0) | |
| } | |
| } | |
| extension UIColor { | |
| convenience init(hexString: String) { | |
| let hexString = hexString.trimmingCharacters(in: .whitespacesAndNewlines) | |
| let scanner = Scanner(string: hexString) | |
| if hexString.hasPrefix("#") { | |
| scanner.scanLocation = 1 | |
| } | |
| let mask: UInt64 = 0xFF | |
| var color: UInt64 = 0 | |
| scanner.scanHexInt64(&color) | |
| let red = (color >> 16) & mask | |
| let green = (color >> 8) & mask | |
| let blue = color & mask | |
| self.init(red: CGFloat(red) / 255.0, | |
| green: CGFloat(green) / 255.0, | |
| blue: CGFloat(blue) / 255.0, | |
| alpha: 1.0) | |
| } | |
| func toHexString() -> String { | |
| var r: CGFloat = 0 | |
| var g: CGFloat = 0 | |
| var b: CGFloat = 0 | |
| var a: CGFloat = 0 | |
| getRed(&r, green: &g, blue: &b, alpha: &a) | |
| let rgb: Int = (Int)(r * 255) << 16 | |
| | (Int)(g * 255) << 8 | |
| | (Int)(b * 255) << 0 | |
| return String(format: "#%06x", rgb) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment