Created
April 9, 2025 01:20
-
-
Save geoffalday/8b0f930fce5412cf1325c7a5b73929c1 to your computer and use it in GitHub Desktop.
Handy Swift Stuff
This file contains hidden or 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 to convert hex color to color that can be used with SwiftUI | |
Usage example: | |
let myColor = "#F8CC45" | |
RoundedRectangle(cornerRadius: 10) | |
.fill(Color(hex: myColor)) | |
*/ | |
extension Color { | |
init(hex: String) { | |
var cleanHexCode = hex.trimmingCharacters(in: .whitespacesAndNewlines) | |
cleanHexCode = cleanHexCode.replacingOccurrences(of: "#", with: "") | |
print(cleanHexCode) | |
var rgb: UInt64 = 0 | |
Scanner(string: cleanHexCode).scanHexInt64(&rgb) | |
let redValue = Double((rgb >> 16) & 0xFF) / 255.0 | |
let greenValue = Double((rgb >> 8) & 0xFF) / 255.0 | |
let blueValue = Double(rgb & 0xFF) / 255.0 | |
self.init(red: redValue, green: greenValue, blue: blueValue) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment