Skip to content

Instantly share code, notes, and snippets.

@ssherar
Last active April 18, 2017 21:05
Show Gist options
  • Save ssherar/deb2536df5f51acc3910 to your computer and use it in GitHub Desktop.
Save ssherar/deb2536df5f51acc3910 to your computer and use it in GitHub Desktop.
UIColorFromRGB - adapted from http://stackoverflow.com/a/12397366 for Swift
/**
Returns a UIColor object from a Hexadecimal string with a solid colour
i.e.
UIColorFromRGB("#FF0000") == UIColor.redColor()
UIColorFromRGB("#0000FF") == UIColor.blueColor()
UIColorFromRGB("#GGGGGG") == UIColor.blackColor()
UIColorFromRGB("#Hello") == UIColor.blackColor()
Adapted from http://stackoverflow.com/a/12397366
:param: color The hexadecimal string representation of the string including the #
:returns: a UIColor, UIColor.blackColor() if the casting fails
*/
func UIColorFromRGB(color: String) -> UIColor {
return UIColorFromRGB(color, 1.0)
}
/**
Returns a UIColor object from a Hexadecimal string with an adjustable alpha channel
i.e.
UIColorFromRGB("#FF0000", 1.0) == UIColor.redColor()
UIColorFromRGB("#0000FF", 1.0) == UIColor.blueColor()
UIColorFromRGB("#GGGGGG", 1.0) == UIColor.blackColor()
UIColorFromRGB("#Hello", 1.0) == UIColor.blackColor()
Adapted from http://stackoverflow.com/a/12397366
:param: color The hexadecimal string representation of the string including the #
:param: alpha The transparency, represented as a Double between 0 and 1
:returns: a UIColor, UIColor.blackColor() if the casting fails
*/
func UIColorFromRGB(color: String, alpha: Double) -> UIColor {
assert(alpha <= 1.0, "The alpha channel cannot be above 1")
assert(alpha >= 0, "The alpha channel cannot be below 0")
var rgbValue : UInt32 = 0
let scanner = NSScanner(string: color)
scanner.scanLocation = 1
if scanner.scanHexInt(&rgbValue) {
let red = CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0
let green = CGFloat((rgbValue & 0xFF00) >> 8) / 255.0
let blue = CGFloat(rgbValue & 0xFF) / 255.0
return UIColor(red: red, green: green, blue: blue, alpha: CGFloat(alpha))
}
return UIColor.blackColor()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment