Skip to content

Commit 69433ed

Browse files
committed
🎨 Hex color init
1 parent 14d2bb4 commit 69433ed

File tree

1 file changed

+26
-0
lines changed
  • Sources/ShinySwiftUI/Extensions/SwiftUI/Color

1 file changed

+26
-0
lines changed

‎Sources/ShinySwiftUI/Extensions/SwiftUI/Color/Color.swift

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,32 @@ import SwiftUI
1010
@available(macOS 11.0, iOS 13.0, *)
1111
public extension Color {
1212

13+
// MARK: - Public Initalizers
14+
15+
init(hex: String) {
16+
let hex = hex.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
17+
var int: UInt64 = 0
18+
Scanner(string: hex).scanHexInt64(&int)
19+
let a, r, g, b: UInt64
20+
switch hex.count {
21+
case 3: // RGB (12-bit)
22+
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
23+
case 6: // RGB (24-bit)
24+
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
25+
case 8: // ARGB (32-bit)
26+
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
27+
default:
28+
(a, r, g, b) = (1, 1, 1, 0)
29+
}
30+
self.init(
31+
.sRGB,
32+
red: Double(r) / 255,
33+
green: Double(g) / 255,
34+
blue: Double(b) / 255,
35+
opacity: Double(a) / 255
36+
)
37+
}
38+
1339
// MARK: - Public Methods
1440

1541
/**

0 commit comments

Comments
 (0)