Skip to content

Instantly share code, notes, and snippets.

@mahmudahsan
Created February 27, 2020 04:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mahmudahsan/fcce94a03aa5a29d07dbfc63a3ce1518 to your computer and use it in GitHub Desktop.
Save mahmudahsan/fcce94a03aa5a29d07dbfc63a3ce1518 to your computer and use it in GitHub Desktop.
SwiftUI how to create color from hex value
extension Color {
static func hexStringToColor (hex:String, opacity: Double = 1.0) -> Color {
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
if ((cString.count) != 6) {
return Color.gray
}
var rgbValue:UInt64 = 0
Scanner(string: cString).scanHexInt64(&rgbValue)
return Color(
red: Double((rgbValue & 0xFF0000) >> 16) / 255.0,
green: Double((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: Double(rgbValue & 0x0000FF) / 255.0,
opacity: Double(opacity)
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment