Created
August 21, 2021 08:19
-
-
Save Shubham0812/fb9427142645b949cd661c26351a2b1a 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 UIKit | |
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