Skip to content

Instantly share code, notes, and snippets.

@Shubham0812
Created July 31, 2021 17:30
Show Gist options
  • Save Shubham0812/f2e281f581547f5ea880276ea5959ab8 to your computer and use it in GitHub Desktop.
Save Shubham0812/f2e281f581547f5ea880276ea5959ab8 to your computer and use it in GitHub Desktop.
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