How to get the RGB Code (INT) from an UIColor in Swift [duplicate]
Solution 1:
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)
}
}
Solution 2:
From Martin R's answer :The method could also return a named tuple (a Swift 2 feature):
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
}
}
}