Last active
March 14, 2018 19:32
-
-
Save adauguet/9f63d5a483bb8ce24e47552c49d6b944 to your computer and use it in GitHub Desktop.
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 | |
extension Int { | |
init?(hexString: String) { | |
let string = hexString.replacingOccurrences(of: "#", with: "") | |
self.init(string, radix: 16) | |
} | |
var rgb: (red: Int, green: Int, blue: Int) { | |
let red = self >> 16 & 0xff | |
let green = self >> 8 & 0xff | |
let blue = self & 0xff | |
return (red, green, blue) | |
} | |
} | |
extension UIColor { | |
convenience init(hex: Int, alpha: CGFloat = 1) { | |
let (red, green, blue) = hex.rgb | |
self.init(red: red, green: green, blue: blue, alpha: alpha) | |
} | |
convenience init(red: Int, green: Int, blue: Int, alpha: CGFloat = 1) { | |
self.init(red: CGFloat(red)/255, green: CGFloat(green)/255, blue: CGFloat(blue)/255, alpha: alpha) | |
} | |
} | |
0xffffff.rgb // (255, 255, 255) | |
0x000000.rgb // (0, 0, 0) | |
UIColor(hex: 0x0000ff) == .blue // true | |
Int(hexString: "#E4723D")?.rgb // (red 228, green 114, blue 61) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment