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 ?
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?
So far I use the following to get the RGB values from it: // rgbs is an array of integers, every single integer represents the // RGB values combined in some way int r = (int) ((Math. pow(256,3) + rgbs[k]) / 65536); int g = (int) (((Math. pow(256,3) + rgbs[k]) / 256 ) % 256 ); int b = (int) ((Math.
Just add the property ColorLiteral as shown in the example, Xcode will prompt you with a whole list of colors which you can choose. The advantage of doing so is lesser code, add HEX values or RGB. You will also get the recently used colors from the storyboard. this is Amazing !
To convert a UIColor instance to a hex value, we define a convenience method, toHex(alpha:) . The method accepts one parameter of type Bool , which indicates whether the alpha value should be included in the string that is returned from the method.
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
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 } } }
Usage:
let swiftColor = UIColor(red: 1, green: 165/255, blue: 0, alpha: 1) if let rgb = swiftColor.rgb() { print(rgb) } else { print("conversion failed") }
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.
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
.
The reverse conversion is
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) } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With