Created
April 4, 2021 07:11
-
-
Save richardwei6/47517da765cc16ff696465774ca00154 to your computer and use it in GitHub Desktop.
UIColor Hex Parser
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
extension UIColor{ | |
convenience init(hex: String, alpha: CGFloat = 1.0){ | |
var hex_copy = hex; | |
let count = hex.count; | |
if (count != 6 && count != 7){ | |
self.init(); | |
return; | |
} | |
if (count == 7){ | |
hex_copy.removeFirst(); | |
} | |
// FFFFFF - FF FF FF | |
let r_s : String = "\(hex_copy[0])\(hex_copy[1])"; | |
let g_s : String = "\(hex_copy[2])\(hex_copy[3])"; | |
let b_s : String = "\(hex_copy[4])\(hex_copy[5])"; | |
//print("hex - \(r_s)\(g_s)\(b_s)") | |
guard let r = UInt8(r_s, radix: 16) else{ | |
self.init(); | |
return; | |
} | |
guard let g = UInt8(g_s, radix: 16) else{ | |
self.init(); | |
return; | |
} | |
guard let b = UInt8(b_s, radix: 16) else{ | |
self.init(); | |
return; | |
} | |
self.init(red: CGFloat(Double(r)/255.0), green: CGFloat(Double(g)/255.0), blue: CGFloat(Double(b)/255.0), alpha: alpha); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment