If I have a SwiftUI Color
:
let col: Color = Color(red: 0.5, green: 0.5, blue: 0.5)
How do I get the RGB components from
I have found that @Mojtaba Hosseinis answer is working fine, except when you have your colors declared inside assets with light and dark appearances.
Then I found that the dark appearance somehow gets lost when using UIColor(self)
. Here is a workaround I came up with:
Note, this is only for iOS
since my app is iOS
only, you could of course do the same as @Mojtaba Hosseini and adapt it to macOS
as well.
extension Color {
var components: (r: Double, g: Double, b: Double, o: Double)? {
let uiColor: UIColor
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var o: CGFloat = 0
if self.description.contains("NamedColor") {
let lowerBound = self.description.range(of: "name: \"")!.upperBound
let upperBound = self.description.range(of: "\", bundle")!.lowerBound
let assetsName = String(self.description[lowerBound..
The idea is to use the UIColor(named:)
initializer instead, where all appearances are correct.
Fortunately, the name we set in assets is saved in the description of the Color
. We only have to abstract it since there is also other information, namely bundle, etc.