如何在Swift中从UIColor获取RGB代码(INT)

我想在Swift中获取UIColor的RGB值:

let swiftColor = UIColor(red: 1, green: 165/255, blue: 0, alpha: 1) println("RGB Value is:"); println(swiftColor.getRGB()); <<<<<< How to do that ? 

在Java中,我会做如下:

 Color cnew = new Color(); int iColor = cnew.rgb(1, 165/255, 0); System.out.println(iColor); 

我应该如何得到这个价值?

Java getRGB()返回一个整数,表示默认sRGB颜色空间中的颜色(位24-31是alpha,16-23是红色,8-15是绿色,0-7是蓝色)。

UIColor没有这样的方法,但是你可以定义你自己的:

 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或图案图像创build的,则可能会失败,在这种情况下返回nil

备注:正如@ vonox7注意到的那样,返回的值在32位平台上可能是负的(Java getRGB()方法也是如此)。 如果不需要,则用UIntInt64replaceInt

从马丁R的答案:该方法还可以返回一个命名的元组(Swift 2function):

 extension UIColor { func rgb() -> (red:Int, green:Int, blue:Int, alpha: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) return (red:iRed, green:iGreen, blue:iBlue, alpha:iAlpha) } else { // Could not extract RGBA components: return nil } } } 

Swift 3.0 IOS 10

 let colour = UIColor.red let rgbColour = colour.cgColor let rgbColours = rgbColour.components 

写了一个可以使用的扩展。 我select将值返回为CGFloat而不是Int因为CGFloat是UIColor的init方法

 extension UIColor { var colorComponents: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat)? { guard let components = self.cgColor.components else { return nil } return ( red: components[0], green: components[1], blue: components[2], alpha: components[3] ) } } 

注意:Swift 3.1 / iOS 10兼容,可能无法在iOS 9中使用,因为UIColor.cgColor.components可能无法使用

Swift 4.从UIColor获取hex代码(UInt):

 extension UIColor { var coreImageColor: CIColor { return CIColor(color: self) } var hex: UInt { let red = UInt(coreImageColor.red * 255 + 0.5) let green = UInt(coreImageColor.green * 255 + 0.5) let blue = UInt(coreImageColor.blue * 255 + 0.5) return (red << 16) | (green << 8) | blue } }