如何从 Swift 中的 UIColor 获取 RGB 代码 (INT) [英] How to get the RGB Code (INT) from an UIColor in Swift
问题描述
我想在 Swift 中获取 UIColor 的 RGB 值:
I would like to get the RGB Value of an UIColor in Swift:
let swiftColor = UIColor(red: 1, green: 165/255, blue: 0, alpha: 1)
println("RGB Value is:");
println(swiftColor.getRGB()); <<<<<< How to do that ?
在 Java 中,我会这样做:
In Java I would do it as follows:
Color cnew = new Color();
int iColor = cnew.rgb(1, 165/255, 0);
System.out.println(iColor);
我应该如何获得这个值?
How should I get this value?
推荐答案
Java getRGB()
返回一个整数,表示默认 sRGB 颜色空间中的颜色(位 24-31 是 alpha,16-23 是红色,8-15 是绿色,0-7 是蓝色).
The Java getRGB()
returns an integer representing the color in the default sRGB color space (bits 24-31 are alpha, 16-23 are red, 8-15 are green, 0-7 are blue).
UIColor
没有这样的方法,但是你可以自己定义:
UIColor
does not have such a method, but you can define your own:
extension UIColor {
func rgb() -> Int? {
var fRed : CGFloat = 0
var fGreen : CGFloat = 0
var fBlue : CGFloat = 0
var fAlpha: CGFloat = 0
if self.getRed(&fRed, green: &fGreen, blue: &fBlue, alpha: &fAlpha) {
let iRed = Int(fRed * 255.0)
let iGreen = Int(fGreen * 255.0)
let iBlue = Int(fBlue * 255.0)
let iAlpha = Int(fAlpha * 255.0)
// (Bits 24-31 are alpha, 16-23 are red, 8-15 are green, 0-7 are blue).
let rgb = (iAlpha << 24) + (iRed << 16) + (iGreen << 8) + iBlue
return rgb
} else {
// Could not extract RGBA components:
return nil
}
}
}
用法:
let swiftColor = UIColor(red: 1, green: 165/255, blue: 0, alpha: 1)
if let rgb = swiftColor.rgb() {
print(rgb)
} else {
print("conversion failed")
}
请注意,这仅在 UIColor
已在RGB 兼容"色彩空间(例如 RGB、HSB 或 GrayScale).它可能如果颜色是从 CIColor
或图案创建的,则失败图像,在这种情况下 nil
被返回.
Note that this will only work if the UIColor
has been defined in an
"RGB-compatible" colorspace (such as RGB, HSB or GrayScale). It may
fail if the color has been created from an CIColor
or a pattern
image, in that case nil
is returned.
备注: 正如@vonox7 所注意到的,返回值可能是负数在 32 位平台上(Java getRGB()
方法也是如此).如果不需要,请将 Int
替换为 UInt
或 Int64
.
Remark: As @vonox7 noticed, the returned value can be negative
on 32-bit platforms (which is also the case with the Java getRGB()
method).
If that is not wanted, replace Int
by UInt
or Int64
.
反向转换是
extension UIColor {
convenience init(rgb: Int) {
let iBlue = rgb & 0xFF
let iGreen = (rgb >> 8) & 0xFF
let iRed = (rgb >> 16) & 0xFF
let iAlpha = (rgb >> 24) & 0xFF
self.init(red: CGFloat(iRed)/255, green: CGFloat(iGreen)/255,
blue: CGFloat(iBlue)/255, alpha: CGFloat(iAlpha)/255)
}
}
这篇关于如何从 Swift 中的 UIColor 获取 RGB 代码 (INT)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!