如何从Color SwiftUI获取RGB组件 [英] How to get RGB components from Color SwiftUI

查看:216
本文介绍了如何从Color SwiftUI获取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 ,但似乎没有

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 或<$ c返回 UIColor 现在,用于 macOS 的$ c> NSColor 。在这些帮助下,您可以实现以下扩展:

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!

这篇关于如何从Color SwiftUI获取RGB组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆