Skip to content

Commit 75b17ae

Browse files
committed
🕵️‍♀️ Color Coddle conformance
1 parent 2606265 commit 75b17ae

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
//
2+
// File.swift
3+
//
4+
//
5+
// Created by Ben Myers on 2/3/22.
6+
//
7+
8+
import SwiftUI
9+
10+
#if os(iOS)
11+
import UIKit
12+
#elseif os(watchOS)
13+
import WatchKit
14+
#elseif os(macOS)
15+
import AppKit
16+
#endif
17+
18+
@available(macOS 11.0, *)
19+
extension Color: Codable {
20+
21+
// MARK: - Inheritance
22+
23+
enum CodingKeys: String, CodingKey {
24+
case red, green, blue
25+
}
26+
27+
public init(from decoder: Decoder) throws {
28+
let container = try decoder.container(keyedBy: CodingKeys.self)
29+
let r = try container.decode(Double.self, forKey: .red)
30+
let g = try container.decode(Double.self, forKey: .green)
31+
let b = try container.decode(Double.self, forKey: .blue)
32+
33+
self.init(red: r, green: g, blue: b)
34+
}
35+
36+
public func encode(to encoder: Encoder) throws {
37+
guard let colorComponents = self.colorComponents else {
38+
return
39+
}
40+
41+
var container = encoder.container(keyedBy: CodingKeys.self)
42+
43+
try container.encode(colorComponents.red, forKey: .red)
44+
try container.encode(colorComponents.green, forKey: .green)
45+
try container.encode(colorComponents.blue, forKey: .blue)
46+
}
47+
}
48+
49+
50+
@available(macOS 11.0, *)
51+
fileprivate extension Color {
52+
#if os(macOS)
53+
typealias SystemColor = NSColor
54+
#else
55+
typealias SystemColor = UIColor
56+
#endif
57+
58+
var colorComponents: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat)? {
59+
var r: CGFloat = 0
60+
var g: CGFloat = 0
61+
var b: CGFloat = 0
62+
var a: CGFloat = 0
63+
64+
#if os(macOS)
65+
SystemColor(self).getRed(&r, green: &g, blue: &b, alpha: &a)
66+
// Note that non RGB color will raise an exception, that I don't now how to catch because it is an Objc exception.
67+
#else
68+
guard SystemColor(self).getRed(&r, green: &g, blue: &b, alpha: &a) else {
69+
// Pay attention that the color should be convertible into RGB format
70+
// Colors using hue, saturation and brightness won't work
71+
return nil
72+
}
73+
#endif
74+
75+
return (r, g, b, a)
76+
}
77+
}

0 commit comments

Comments
 (0)