Color+Extension.swift
1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//
// Color+Extension.swift
// hippo-watch Watch App
//
// Created by shihao on 2025/7/10.
//
import Foundation
import SwiftUI
extension Color {
init(hex: String) {
let hex = hex.trimmingCharacters(in: .whitespacesAndNewlines)
.replacingOccurrences(of: "#", with: "")
var int = UInt64()
guard Scanner(string: hex).scanHexInt64(&int) else {
self.init(.sRGB, red: 0, green: 0, blue: 0, opacity: 1)
return
}
let a, r, g, b: UInt64
switch hex.count {
case 8: // AARRGGBB
a = (int & 0xFF000000) >> 24
r = (int & 0x00FF0000) >> 16
g = (int & 0x0000FF00) >> 8
b = int & 0x000000FF
case 6: // RRGGBB
a = 255
r = (int & 0xFF0000) >> 16
g = (int & 0x00FF00) >> 8
b = int & 0x0000FF
case 3: // RGB (短格式)
a = 255
r = ((int & 0xF00) >> 8) * 17
g = ((int & 0x0F0) >> 4) * 17
b = (int & 0x00F) * 17
default:
a = 255; r = 0; g = 0; b = 0
}
self.init(
.sRGB,
red: Double(r) / 255,
green: Double(g) / 255,
blue: Double(b) / 255,
opacity: Double(a) / 255
)
}
}
struct RectCorner: OptionSet {
let rawValue: Int
static let topLeft = RectCorner(rawValue: 1 << 0)
static let topRight = RectCorner(rawValue: 1 << 1)
static let bottomLeft = RectCorner(rawValue: 1 << 2)
static let bottomRight = RectCorner(rawValue: 1 << 3)
}
extension View {
func cornerRadius(_ radius: CGFloat, corners: RectCorner) -> some View {
clipShape(RoundedRectangle(cornerRadius: radius))
}
}