SwiftUI `ColorPicker` load and save values to disk using `AppStorage`
// | |
// ContentView.swift | |
// Shared | |
// | |
// Created by Dan Tavares on 17/07/2020. | |
// | |
import SwiftUI | |
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 { | |
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: UIColor(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
This comment has been minimized.
Thank you!