如何从 SwiftUI 中的 Color 获取 RGB 组件 [英] How to get RGB components from Color in SwiftUI
本文介绍了如何从 SwiftUI 中的 Color 获取 RGB 组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个 SwiftUI Color
:
If I have a SwiftUI Color
:
let col: Color = Color(red: 0.5, green: 0.5, blue: 0.5)
如何从 col
获取 RGB 分量?
可能是这样:
How do I get the RGB components from col
?
Like this maybe:
print(col.components.red)
在 UIKit 中,我可以使用 UIColor.getRed
但在 SwiftUI 中似乎没有等价物.
In UIKit, I could use UIColor.getRed
but there doesn't seem to be an equivalent in SwiftUI.
推荐答案
iOS 14/macOS 10.16
有一个新的初始化器,它采用 Color
并为 iOS 或 NSColor
返回 UIColor
为 <强>macOS 现在.在这些人的帮助下,您可以实现以下扩展:
iOS 14 / macOS 10.16
There is a new initializer that takes a Color
and returns a UIColor
for iOS or NSColor
for macOS now. With the help of those you can implement the following extensions:
import SwiftUI
#if canImport(UIKit)
import UIKit
#elseif canImport(AppKit)
import AppKit
#endif
extension Color {
var components: (red: CGFloat, green: CGFloat, blue: CGFloat, opacity: CGFloat) {
#if canImport(UIKit)
typealias NativeColor = UIColor
#elseif canImport(AppKit)
typealias NativeColor = NSColor
#endif
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var o: CGFloat = 0
guard NativeColor(self).getRed(&r, green: &g, blue: &b, alpha: &o) else {
// You can handle the failure here as you want
return (0, 0, 0, 0)
}
return (r, g, b, o)
}
}
用法
Color.red.components.red // 0.9999999403953552 // <- SwiftUI Colors are not pure!
这篇关于如何从 SwiftUI 中的 Color 获取 RGB 组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文