Forked from vibrazy/ColorPickerStorageExample.swift
Created
January 28, 2023 18:19
-
-
Save recoveryawareness/1284d2b5f5fe35af14da4dcfbf2015a9 to your computer and use it in GitHub Desktop.
SwiftUI `ColorPicker` load and save values to disk using `AppStorage`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| // ContentView.swift | |
| // Shared | |
| // | |
| // Created by Dan Tavares on 01/07/2022. | |
| // More Info: https://nilcoalescing.com/blog/EncodeAndDecodeSwiftUIColor/ | |
| import SwiftUI | |
| #if os(iOS) | |
| typealias PlatformColor = UIColor | |
| extension Color { | |
| init(platformColor: PlatformColor) { | |
| self.init(uiColor: platformColor) | |
| } | |
| } | |
| #elseif os(macOS) | |
| typealias PlatformColor = NSColor | |
| extension Color { | |
| init(platformColor: PlatformColor) { | |
| self.init(nsColor: platformColor) | |
| } | |
| } | |
| #endif | |
| struct ContentView: View { | |
| @AppStorage("color") var color: Color = Color.white | |
| var body: some View { | |
| ZStack { | |
| color.edgesIgnoringSafeArea(.all) | |
| ColorPicker("Background color", selection: $color) | |
| .padding() | |
| } | |
| } | |
| } | |
| extension Color: RawRepresentable { | |
| // TODO: Sort out alpha | |
| public init?(rawValue: Int) { | |
| let red = Double((rawValue & 0xFF0000) >> 16) / 0xFF | |
| let green = Double((rawValue & 0x00FF00) >> 8) / 0xFF | |
| let blue = Double(rawValue & 0x0000FF) / 0xFF | |
| self = Color(red: red, green: green, blue: blue) | |
| } | |
| public var rawValue: Int { | |
| guard let coreImageColor = coreImageColor else { | |
| return 0 | |
| } | |
| let red = Int(coreImageColor.red * 255 + 0.5) | |
| let green = Int(coreImageColor.green * 255 + 0.5) | |
| let blue = Int(coreImageColor.blue * 255 + 0.5) | |
| return (red << 16) | (green << 8) | blue | |
| } | |
| private var coreImageColor: CIColor? { | |
| return CIColor(color: PlatformColor(self)) | |
| } | |
| } | |
| struct ContentView_Previews: PreviewProvider { | |
| static var previews: some View { | |
| ContentView() | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment