Last active
May 15, 2024 04:45
-
-
Save PJayRushton/8e09c773e3c1ee9eed133d28e13add77 to your computer and use it in GitHub Desktop.
SwiftUI Color + Hex Extensions
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
import SwiftUI | |
extension Color { | |
var hexString: String { | |
let cg = UIColor(self).cgColor | |
let components = cg.components | |
let r: CGFloat = components?[0] ?? 0.0 | |
let g: CGFloat = components?[1] ?? 0.0 | |
let b: CGFloat = components?[2] ?? 0.0 | |
return String.init(format: "#%02lX%02lX%02lX", lroundf(Float(r * 255)), lroundf(Float(g * 255)), lroundf(Float(b * 255))) | |
} | |
init?(hex: String) { | |
let r, g, b, a: CGFloat | |
guard hex.hasPrefix("#") else { | |
return nil | |
} | |
let start = hex.index(hex.startIndex, offsetBy: 1) | |
let hexColor = String(hex[start...]) | |
guard hexColor.count == 6 else { | |
return nil | |
} | |
let scanner = Scanner(string: hexColor) | |
var hexNumber: UInt64 = 0 | |
if scanner.scanHexInt64(&hexNumber) { | |
r = CGFloat((hexNumber & 0xff000000) >> 24) / 255 | |
g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255 | |
b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255 | |
a = CGFloat(hexNumber & 0x000000ff) / 255 | |
let uiColor = UIColor(red: r, green: g, blue: b, alpha: a) | |
self.init(uiColor: uiColor) | |
} else { | |
return nil | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment