Skip to content

Instantly share code, notes, and snippets.

@amfathi
Last active March 20, 2021 12:22
Show Gist options
  • Save amfathi/04174c26c95fb4b918f517f2969fb3e4 to your computer and use it in GitHub Desktop.
Save amfathi/04174c26c95fb4b918f517f2969fb3e4 to your computer and use it in GitHub Desktop.
import UIKit
extension UIColor {
public convenience init?(hex: String) {
let r, g, b: CGFloat
if hex.hasPrefix("#") {
let start = hex.index(hex.startIndex, offsetBy: 1)
let hexColor = String(hex[start...])
if hexColor.count == 6 {
let scanner = Scanner(string: hexColor)
var hexNumber: UInt64 = 0
if scanner.scanHexInt64(&hexNumber) {
r = CGFloat((hexNumber & 0xff0000) >> 16) / 255
g = CGFloat((hexNumber & 0x00ff00) >> 8) / 255
b = CGFloat((hexNumber & 0x0000ff)) / 255
self.init(red: r, green: g, blue: b, alpha: 1)
return
}
} else if hexColor.count == 3 {
let scanner = Scanner(string: hexColor)
var hexNumber: UInt64 = 0
if scanner.scanHexInt64(&hexNumber) {
r = CGFloat(((hexNumber & 0xf00) >> 8) + ((hexNumber & 0xf00) >> 4)) / 255
g = CGFloat((hexNumber & 0x0f0) + ((hexNumber & 0x0f0) >> 4)) / 255
b = CGFloat((hexNumber & 0x00f) + (hexNumber & 0x00f) << 4) / 255
self.init(red: r, green: g, blue: b, alpha: 1)
return
}
}
}
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment