forked from JohJakob/Setting
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtilities.swift
More file actions
95 lines (80 loc) · 2.63 KB
/
Utilities.swift
File metadata and controls
95 lines (80 loc) · 2.63 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
//
// Utilities.swift
// SettingExample
//
// Created by A. Zheng (github.com/aheze) on 2/22/23.
// Copyright © 2023 A. Zheng. All rights reserved.
//
import SwiftUI
extension Color {
init(hex: Int, alpha: Double = 1) {
self.init(
.sRGB,
red: Double((hex >> 16) & 0xFF) / 255,
green: Double((hex >> 08) & 0xFF) / 255,
blue: Double((hex >> 00) & 0xFF) / 255,
opacity: alpha
)
}
var hex: UInt {
return getHex() ?? 0x00AEEF
}
/// from https://stackoverflow.com/a/28645384/14351818
func getHex() -> UInt? {
var fRed: CGFloat = 0
var fGreen: CGFloat = 0
var fBlue: CGFloat = 0
var fAlpha: CGFloat = 0
#if os(iOS)
let color = UIColor(self)
if color.getRed(&fRed, green: &fGreen, blue: &fBlue, alpha: &fAlpha) {
fRed = fRed.clamped(to: 0 ... 1)
fGreen = fGreen.clamped(to: 0 ... 1)
fBlue = fBlue.clamped(to: 0 ... 1)
let iRed = UInt(fRed * 255.0)
let iGreen = UInt(fGreen * 255.0)
let iBlue = UInt(fBlue * 255.0)
// (Bits 24-31 are alpha, 16-23 are red, 8-15 are green, 0-7 are blue).
let hex = (iRed << 16) + (iGreen << 8) + iBlue
return hex
} else {
// Could not extract RGBA components:
return nil
}
#else
let color = NSColor(self)
color.getRed(&fRed, green: &fGreen, blue: &fBlue, alpha: &fAlpha)
fRed = fRed.clamped(to: 0 ... 1)
fGreen = fGreen.clamped(to: 0 ... 1)
fBlue = fBlue.clamped(to: 0 ... 1)
let iRed = UInt(fRed * 255.0)
let iGreen = UInt(fGreen * 255.0)
let iBlue = UInt(fBlue * 255.0)
// (Bits 24-31 are alpha, 16-23 are red, 8-15 are green, 0-7 are blue).
let hex = (iRed << 16) + (iGreen << 8) + iBlue
return hex
#endif
}
}
extension Comparable {
/// used for the UIColor
func clamped(to limits: ClosedRange<Self>) -> Self {
return min(max(self, limits.lowerBound), limits.upperBound)
}
}
public extension View {
@inlinable
func reverseMask<Mask: View>(
padding: CGFloat = 0, /// extra negative padding for shadows
@ViewBuilder _ mask: () -> Mask
) -> some View {
self.mask(
Rectangle()
.padding(-padding)
.overlay(
mask()
.blendMode(.destinationOut)
)
)
}
}