Created
February 6, 2019 17:48
-
-
Save noahsark769/d0f8f4a16b1aadcb60298ed7b7fc136e to your computer and use it in GitHub Desktop.
Instantiate a UIColor from a hex string with 6 or 8 chars
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 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