Skip to content

Instantly share code, notes, and snippets.

@noahsark769
Created February 6, 2019 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noahsark769/d0f8f4a16b1aadcb60298ed7b7fc136e to your computer and use it in GitHub Desktop.
Save noahsark769/d0f8f4a16b1aadcb60298ed7b7fc136e to your computer and use it in GitHub Desktop.
Instantiate a UIColor from a hex string with 6 or 8 chars
extension UIColor {
// Adapted from https://gist.github.com/yannickl/16f0ed38f0698d9a8ae7, modified to accept alpha
// values. Works with strings with or without "#", 6 char strings like "a735b5", 8 char strings
// with alpha value like "836be64"
convenience init(hexString: String) {
let hexString = hexString.trimmingCharacters(in: .whitespacesAndNewlines)
let scanner = Scanner(string: hexString)
if (hexString.hasPrefix("#")) {
scanner.scanLocation = 1
}
let initialPosition = scanner.scanLocation
var color: UInt32 = 0
scanner.scanHexInt32(&color)
let numCharsScanned = scanner.scanLocation - initialPosition
let alphaOffset = numCharsScanned == 8 ? 8 : 0
let mask = 0x000000FF
let r = Int(color >> (16 + alphaOffset)) & mask
let g = Int(color >> (8 + alphaOffset)) & mask
let b = Int(color >> (alphaOffset)) & mask
let red = CGFloat(r) / 255.0
let green = CGFloat(g) / 255.0
let blue = CGFloat(b) / 255.0
let alpha: CGFloat
if alphaOffset > 0 {
let a = Int(color) & mask
alpha = CGFloat(a) / 255.0
} else {
alpha = 1
}
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment