How to Get Rgb Values from Uicolor

How to get RGB values from UIColor?


const CGFloat *colors = CGColorGetComponents( curView.backgroundColor.CGColor );

These links provide further details:

  • UIColor Reference
  • CGColorGetComponents reference

Extract RGB Values From UIColor

You can convert UIColor to CIColor and then extract the color components from it as follow:

Update: Xcode 8.3.2 • Swift 3.1

extension UIColor {
var coreImageColor: CIColor {
return CIColor(color: self)
}
var components: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
let coreImageColor = self.coreImageColor
return (coreImageColor.red, coreImageColor.green, coreImageColor.blue, coreImageColor.alpha)
}
}

usage:

let myColor = UIColor(red: 0.5, green: 1, blue: 0.25, alpha: 0.5)
let myCIColor = myColor.coreImageColor
let greencomponent = myColor.components.green
let myColorComponents = myColor.components
print(myColorComponents.red) // 0.5
print(myColorComponents.green) // 1.0
print(myColorComponents.blue) // 0.25
print(myColorComponents.alpha) // 0.5



You can also use the function getRed() and create an extension to extract the components as follow but the result would be optional:

extension UIColor {
typealias RGBA = (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat)
var rgba: RGBA? {
var (r, g, b, a): RGBA = (0, 0, 0, 0)
return getRed(&r, green: &g, blue: &b, alpha: &a) ? (r,g,b,a) : nil
}
var r: CGFloat? {
var red: CGFloat = .zero
return getRed(&red, green: nil, blue: nil, alpha: nil) ? red : nil
}
var g: CGFloat? {
var green: CGFloat = .zero
return getRed(nil, green: &green, blue: nil, alpha: nil) ? green : nil
}
var b: CGFloat? {
var blue: CGFloat = .zero
return getRed(nil, green: nil, blue: &blue, alpha: nil) ? blue : nil
}
var a: CGFloat? {
var alpha: CGFloat = .zero
return getRed(nil, green: nil, blue: nil, alpha: &alpha) ? alpha : nil
}
}

Usage

let color = UIColor(red: 0.5, green: 1, blue: 0.25, alpha: 0.5)
if let components = color.rgba {
print(components.red) // 0.5
print(components.green) // 1.0
print(components.blue) // 0.25
print(components.alpha) // 0.5
}

print(color.r ?? "nil") // 0.5
print(color.g ?? "nil") // 1.0
print(color.b ?? "nil") // 0.25
print(color.a ?? "nil") // 0.5

How to get the RGB Code (INT) from an UIColor in Swift

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)
}
}

Get RGB value from UIColor presets

UIColor has a method which gives you the RGB components (-getRed:green:blue:alpha:) which works great on iOS 7 or higher. On iOS 6 and earlier, this method will fail and return NO if the color is not in an RGB color space (as it will for [UIColor grayColor].)

For iOS 6 and earlier, the only way I know of for doing this that works in all color spaces is to create a Core Graphics bitmap context in an RGB color space and draw into it with your color. You can then read out the RGB values from the resulting bitmap. Note that this won't work for certain colors, like pattern colors (eg. [UIColor groupTableViewBackgroundColor]), which don't have reasonable RGB values.

- (void)getRGBComponents:(CGFloat [3])components forColor:(UIColor *)color {
CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char resultingPixel[4];
CGContextRef context = CGBitmapContextCreate(&resultingPixel,
1,
1,
8,
4,
rgbColorSpace,
kCGImageAlphaNoneSkipLast);
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, CGRectMake(0, 0, 1, 1));
CGContextRelease(context);
CGColorSpaceRelease(rgbColorSpace);

for (int component = 0; component < 3; component++) {
components[component] = resultingPixel[component] / 255.0f;
}
}

You can use it something like this:

    CGFloat components[3];
[self getRGBComponents:components forColor:[UIColor grayColor]];
NSLog(@"%f %f %f", components[0], components[1], components[2]);

How can I access the RGB values of a UIColor?

Use getRed(_:green:blue:alpha:):

var red:   CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0

color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)

How to get RGB components from Color in SwiftUI


iOS 14 / macOS 10.16

There is a new initializer that takes a Color and returns a UIColor for iOS or NSColor for macOS now. With the help of those you can implement the following extensions:

iOS / macOS

import SwiftUI

#if canImport(UIKit)
import UIKit
#elseif canImport(AppKit)
import AppKit
#endif

extension Color {
var components: (red: CGFloat, green: CGFloat, blue: CGFloat, opacity: CGFloat) {

#if canImport(UIKit)
typealias NativeColor = UIColor
#elseif canImport(AppKit)
typealias NativeColor = NSColor
#endif

var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var o: CGFloat = 0

guard NativeColor(self).getRed(&r, green: &g, blue: &b, alpha: &o) else {
// You can handle the failure here as you want
return (0, 0, 0, 0)
}

return (r, g, b, o)
}
}


Usage

Color.red.components.red // 0.9999999403953552 // <- SwiftUI Colors are not pure!

Getting RGB values from UIColors derived from Hex colors

The problem is with the example you give. The color #CCCCCC is a greyscale color meaning the UIColor is not created with RGB but with a grey. In other words, it is created with UIColor colorWithWhite:alpha:. Since your UIColor is created with a different color model than RGB, using getRed:green:blue:alpha: returns NO.

What you can do is this:-

UIColor *color =  // your color
CGFloat red, green, blue, alpha;

if (![color getRed:&red green:&green blue:&blue alpha:&alpha]) {

CGFloat white;
if ([color getWhite:&white alpha:&alpha]) {
red = green = blue = white;
} else {
NSLog(@"Uh oh, not RGB or greyscale");
}
}

Update:

It seems that the behavior changed a bit as of iOS 8. The RGB values of a color created with UIColor colorWithWhite:alpha: can be obtained with UIColor getRed:green:blue:alpha:. In earlier versions of iOS, this didn't work. Hence the need for the code I originally posted.

How can I use UIColorFromRGB in Swift?

Here's a Swift version of that function (for getting a UIColor representation of a UInt value):

func UIColorFromRGB(rgbValue: UInt) -> UIColor {
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}

view.backgroundColor = UIColorFromRGB(0x209624)


Related Topics



Leave a reply



Submit