Skip to content

Instantly share code, notes, and snippets.

@Joony
Created October 13, 2022 08:54
Show Gist options
  • Save Joony/f77b0aea88e836e73b92d3a94060102e to your computer and use it in GitHub Desktop.
Save Joony/f77b0aea88e836e73b92d3a94060102e to your computer and use it in GitHub Desktop.
A SwiftUI extension of Color to add Int/String representation for storage
extension Color {
var sRGBA: Int {
guard let components = UIColor(self).cgColor.components?.map({ Int(0xFF * $0) }) else { return 0 }
return (components[3] << 24) | (components[0] << 16) | (components[1] << 8) | components[2]
}
var hex: String {
String(sRGBA, radix: 16, uppercase: true)
}
var named: String {
UIColor(self).accessibilityName
}
init(sRGBA: Int) {
self = .init(
red: Double((sRGBA & 0xFF0000) >> 16) / 0xFF,
green: Double((sRGBA & 0x00FF00) >> 8) / 0xFF,
blue: Double(sRGBA & 0x0000FF) / 0xFF,
opacity: Double((sRGBA & 0xFF000000) >> 24) / 0xFF
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment