Created
February 27, 2020 04:42
-
-
Save mahmudahsan/fcce94a03aa5a29d07dbfc63a3ce1518 to your computer and use it in GitHub Desktop.
SwiftUI how to create color from hex value
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 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