Created
May 18, 2022 05:18
-
-
Save zs40x/ad179456dca54bb27960150955deb30b 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 { | |
public static func fromHexString (_ hex: String) -> Color { | |
let hexString = prepareHexString(hex) | |
guard hexString.count == 6 else { return Color.gray } | |
return Color(makeUIColorFromRgbValue(makeHexInteger(hexString))) | |
} | |
private static func prepareHexString(_ hexString: String) -> String { | |
var preparedHexString = hexString.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() | |
if (preparedHexString.hasPrefix("#")) { | |
preparedHexString.remove(at: preparedHexString.startIndex) | |
} | |
return preparedHexString | |
} | |
private static func makeHexInteger(_ hexString: String) -> UInt64 { | |
var rgbValue: UInt64 = 0 | |
Scanner(string: hexString).scanHexInt64(&rgbValue) | |
return rgbValue | |
} | |
private static func makeUIColorFromRgbValue(_ rgbValue: UInt64) -> UIColor { | |
UIColor( | |
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, | |
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, | |
blue: CGFloat(rgbValue & 0x0000FF) / 255.0, | |
alpha: CGFloat(1.0)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment