|
1 | 1 | import SwiftUI |
2 | 2 | import SwiftBoost |
3 | 3 |
|
4 | | -extension View { |
| 4 | +extension Color { |
| 5 | + |
| 6 | + public init(hex string: String) { |
| 7 | + var string: String = string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) |
| 8 | + if string.hasPrefix("#") { |
| 9 | + _ = string.removeFirst() |
| 10 | + } |
| 11 | + |
| 12 | + // Double the last value if incomplete hex |
| 13 | + if !string.count.isMultiple(of: 2), let last = string.last { |
| 14 | + string.append(last) |
| 15 | + } |
| 16 | + |
| 17 | + // Fix invalid values |
| 18 | + if string.count > 8 { |
| 19 | + string = String(string.prefix(8)) |
| 20 | + } |
| 21 | + |
| 22 | + // Scanner creation |
| 23 | + let scanner = Scanner(string: string) |
| 24 | + |
| 25 | + var color: UInt64 = 0 |
| 26 | + scanner.scanHexInt64(&color) |
| 27 | + |
| 28 | + if string.count == 2 { |
| 29 | + let mask = 0xFF |
| 30 | + |
| 31 | + let g = Int(color) & mask |
| 32 | + |
| 33 | + let gray = Double(g) / 255.0 |
| 34 | + |
| 35 | + self.init(.sRGB, red: gray, green: gray, blue: gray, opacity: 1) |
| 36 | + |
| 37 | + } else if string.count == 4 { |
| 38 | + let mask = 0x00FF |
| 39 | + |
| 40 | + let g = Int(color >> 8) & mask |
| 41 | + let a = Int(color) & mask |
| 42 | + |
| 43 | + let gray = Double(g) / 255.0 |
| 44 | + let alpha = Double(a) / 255.0 |
| 45 | + |
| 46 | + self.init(.sRGB, red: gray, green: gray, blue: gray, opacity: alpha) |
| 47 | + |
| 48 | + } else if string.count == 6 { |
| 49 | + let mask = 0x0000FF |
| 50 | + let r = Int(color >> 16) & mask |
| 51 | + let g = Int(color >> 8) & mask |
| 52 | + let b = Int(color) & mask |
| 53 | + |
| 54 | + let red = Double(r) / 255.0 |
| 55 | + let green = Double(g) / 255.0 |
| 56 | + let blue = Double(b) / 255.0 |
| 57 | + |
| 58 | + self.init(.sRGB, red: red, green: green, blue: blue, opacity: 1) |
| 59 | + |
| 60 | + } else if string.count == 8 { |
| 61 | + let mask = 0x000000FF |
| 62 | + let r = Int(color >> 24) & mask |
| 63 | + let g = Int(color >> 16) & mask |
| 64 | + let b = Int(color >> 8) & mask |
| 65 | + let a = Int(color) & mask |
| 66 | + |
| 67 | + let red = Double(r) / 255.0 |
| 68 | + let green = Double(g) / 255.0 |
| 69 | + let blue = Double(b) / 255.0 |
| 70 | + let alpha = Double(a) / 255.0 |
| 71 | + |
| 72 | + self.init(.sRGB, red: red, green: green, blue: blue, opacity: alpha) |
| 73 | + |
| 74 | + } else { |
| 75 | + self.init(.sRGB, red: 1, green: 1, blue: 1, opacity: 1) |
| 76 | + } |
| 77 | + } |
| 78 | +} |
5 | 79 |
|
6 | | - #if canImport(UIKit) |
| 80 | + |
| 81 | +extension View { |
| 82 | + |
| 83 | +#if canImport(UIKit) |
7 | 84 | @available(iOS 15.0, watchOS 8.0, *) |
8 | 85 | public func foregroundColor(_ color: UIColor) -> some View { |
9 | 86 | self.foregroundColor(.init(uiColor: color)) |
10 | 87 | } |
11 | | - #endif |
| 88 | +#endif |
12 | 89 | } |
0 commit comments