Created
July 31, 2021 17:30
-
-
Save Shubham0812/f2e281f581547f5ea880276ea5959ab8 to your computer and use it in GitHub Desktop.
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
import SwiftUI | |
extension Color { | |
init(hex: String) { | |
self.init(UIColor(hex: hex)) | |
} | |
static func randomColor() -> Color { | |
return Color(UIColor.random()) | |
} | |
} | |
extension UIColor { | |
/// For converting Hex-based colors | |
convenience init(hex: String) { | |
var hexSanitized = hex.trimmingCharacters(in: .whitespacesAndNewlines) | |
hexSanitized = hexSanitized.replacingOccurrences(of: "#", with: "") | |
var rgb: UInt64 = 0 | |
var r: CGFloat = 0.0 | |
var g: CGFloat = 0.0 | |
var b: CGFloat = 0.0 | |
var a: CGFloat = 1.0 | |
let length = hexSanitized.count | |
Scanner(string: hexSanitized).scanHexInt64(&rgb) | |
if length == 6 { | |
r = CGFloat((rgb & 0xFF0000) >> 16) / 255.0 | |
g = CGFloat((rgb & 0x00FF00) >> 8) / 255.0 | |
b = CGFloat(rgb & 0x0000FF) / 255.0 | |
} else if length == 8 { | |
r = CGFloat((rgb & 0xFF000000) >> 24) / 255.0 | |
g = CGFloat((rgb & 0x00FF0000) >> 16) / 255.0 | |
b = CGFloat((rgb & 0x0000FF00) >> 8) / 255.0 | |
a = CGFloat(rgb & 0x000000FF) / 255.0 | |
} | |
self.init(red: r, green: g, blue: b, alpha: a) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment