我想获得一个UIColor在Swift的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(),但你可以
定义自己:
原文链接:https://www.f2er.com/swift/320894.html定义自己:
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,alpha: 1) if let rgb = swiftColor.rgb() { print(rgb) } else { print("conversion Failed") }
注意,这只有在UIColor已定义在“RGB兼容”颜色空间(例如RGB,HSB或GrayScale)。它可能如果颜色是从CIColor或图案创建的,则失败图像,在这种情况下返回nil。