Get Value from SwiftUI Color Picker

Viewed 1184

iOS 14 shipped with native color pickers for UIKit (UIColorWell), AppKit (NSColorWell) and SwiftUI (ColorPicker).

While the color wells have a property selectedColor that exposes the selected UIColor/NSColor values, the SwiftUI ColorPicker takes a Binding<Color>. However, I can't find any information how to get anything useful from the Color value.

Creating a Color from a UIColor is easy using Color.init(_: UIColor) but there does not seem to be a way to get a UIColor from an existing Color or to extract the color components (e.g. the RGB values similar to the UIColor.getRed(_:green:blue:alpha:) method).

How do I get the underlying color values from a SwiftUI ColorPicker?

2 Answers

In majority of cases you use Color in SwiftUI directly, ie it is not needed to extract anything from it.

Anyway if it is needed to have UIColor SwiftUI 2.0 provides new API for that

extension UIColor {

    @available(iOS 14.0, tvOS 14.0, watchOS 7.0, *)
    @available(OSX, unavailable)
    public convenience init(_ color: Color)
}
import SwiftUI
extension Color {
    struct Components {
        var r, g, b, a: Double
    }
    
    var components: Components? {
        guard let components = UIColor(self).cgColor.components?.compactMap(Double.init),
              components.count == 4
        else { return nil}
        return Components(r: components[0], g: components[1], b: components[2], a: components[3])
    }
}
// Usage
print(Color.primary.components)
Related