Skip to content

Instantly share code, notes, and snippets.

@aqubi
Last active November 12, 2021 08:10
Show Gist options
  • Save aqubi/212cf6dd50dc870d394d8c9f4f8bb547 to your computer and use it in GitHub Desktop.
Save aqubi/212cf6dd50dc870d394d8c9f4f8bb547 to your computer and use it in GitHub Desktop.
extension UIColor {
convenience init?(hexString: String) {
let hexString = hexString.trimmingCharacters(in: .whitespacesAndNewlines)
let scanner = Scanner(string: hexString)
scanner.charactersToBeSkipped = CharacterSet(charactersIn: "#")
var color: UInt64 = 0
if scanner.scanHexInt64(&color) {
self.init(hex: color, useOpacity: hexString.count > 7)
} else {
return nil
}
}
convenience init(hex: UInt64, useOpacity: Bool = false) {
let mask = UInt64(0xFF)
let cap = !useOpacity && hex > 0xffffff ? 0xffffff : hex
let r = cap >> (useOpacity ? 24 : 16) & mask
let g = cap >> (useOpacity ? 16 : 8) & mask
let b = cap >> (useOpacity ? 8 : 0) & mask
let a = useOpacity ? cap & mask : 255
self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(a) / 255.0)
}
func toHexString() -> String {
var target = self.cgColor
if let name = cgColor.colorSpace?.name, name != CGColorSpace.sRGB {
let colorSpace = CGColorSpace(name: CGColorSpace.sRGB)!
if let sRGBColor = cgColor.converted(to: colorSpace, intent: .defaultIntent, options: nil) {
target = sRGBColor
}
}
let ciColor = CIColor(cgColor: target)
let r = lroundf(Float(ciColor.red) * 255)
let g = lroundf(Float(ciColor.green) * 255)
let b = lroundf(Float(ciColor.blue) * 255)
let a = lroundf(Float(ciColor.alpha) * 255)
if a != 255 {
return String(format: "#%02lX%02lX%02lX%02lX", r, g, b, a)
} else {
return String(format: "#%02lX%02lX%02lX", r, g, b)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment