How to convert UIColor to SwiftUI‘s Color
Both iOS and macOS
Color
has a native initializer for it that takes an UIColor
or NSColor
as an argument:
Color(.red) /* or any other UIColor/NSColor you need INSIDE parentheses */
DO NOT call Color(UIColor.red)
explicitly !!!. This will couple your SwiftUI code to the UIKit
. Instead, just call Color(.red)
That will infer the correct module automatically.
Also, Note this difference:
Color.red /* this `red` is SwiftUI native `red` */Color(.red) /* this `red` is UIKit `red` */
Note that:
Color.red
and UIColor.red
are NOT same! They have different values and look different with each other. So DON'T assume this worth nothing
These are equal instead: SwiftUI.Color.Red == UIKit.UIColor.systemRed
Also, You can check out How to get RGB components from SwiftUI.Color
Extension
You can implement a custom variable for it to make it more like cgColor
and ciColor
extension UIColor { /// The SwiftUI color associated with the receiver. var suColor: Color { Color(self) }}
so it would be like:
UIColor.red // UIKit colorUIColor.red.suColor // SwiftUI colorUIColor.red.cgColor // Core graphic colorUIColor.red.ciColor // Core image color
Note: Click here to see How to convert SwiftUI.Color
to UIColor
Using two helper extensions:
To extract components from UIColor
:
extension UIColor { var rgba: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) { var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 var alpha: CGFloat = 0 getRed(&red, green: &green, blue: &blue, alpha: &alpha) return (red, green, blue, alpha) }}
To init
with UIColor
:
extension Color { init(uiColor: UIColor) { self.init(red: Double(uiColor.rgba.red), green: Double(uiColor.rgba.green), blue: Double(uiColor.rgba.blue), opacity: Double(uiColor.rgba.alpha)) }}
Usage:
Color(uiColor: .red)