Created
November 10, 2015 20:04
-
-
Save CanTheAlmighty/f3b0a15b6104dbd13b9c to your computer and use it in GitHub Desktop.
UIColor initializer from Hex number, in swift.
This file contains 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 | |
{ | |
class func components(alphaHex hex : UInt32) -> (r:UInt8, g:UInt8, b:UInt8, a:UInt8) | |
{ | |
let r = UInt8((hex & 0xFF000000) >> 24) | |
let g = UInt8((hex & 0x00FF0000) >> 16) | |
let b = UInt8((hex & 0x0000FF00) >> 8) | |
let a = UInt8((hex & 0x000000FF)) | |
return (r,g,b,a) | |
} | |
/// Creates a UIColor from a 0xRRGGBBAA value | |
convenience init(alphaHex hex : UInt32) | |
{ | |
let (r,g,b,a) = UIColor.components(alphaHex: hex) | |
self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(a) / 255.0) | |
} | |
/// Creates a UIColor from a right-padded UInt32 (0x00RRGGBB or 0xRRGGBB), with optional alpha | |
convenience init(hex : UInt32, alpha : CGFloat = 1.0) | |
{ | |
let (r,g,b,_) = UIColor.components(alphaHex: hex << 8) | |
self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: alpha) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment