Question

So here are the colors I am trying to convert from UIColor to CGColor:

001385 - R:0 G:19 B:133

ca000b - R:202 G:0 B:11

Here is the Blue vs. iOS's rendering: a:enter image description here b:enter image description here

Here is the Red vs. iOS's rendering: aenter image description here"> b: enter image description here

Here is the code I am using to convert the colors: Red:

[[UIColor colorWithRed:202 green:0 blue:11 alpha:1] CGColor]

Blue:

[[UIColor colorWithRed:0 green:19 blue:133 alpha:1] CGColor]

Does anyone know what I am doing wrong?

Was it helpful?

Solution

You need to divide the parameters by 255.0. As noted by @Duncan C, ensure you are dividing by 255.0

[[UIColor colorWithRed:202.0/255.0 green:0 blue:11/255.0 alpha:1] CGColor]


[[UIColor colorWithRed:0 green:19/255.0 blue:133/255.0 alpha:1] CGColor]

OTHER TIPS

A handy Category to add to UIColor:

Then you can do for example: [UIColor R:0 G:19 B:133]

@interface UIColor (RGB)

+(UIColor*)R:(NSUInteger)r G:(NSUInteger)g B:(NSUInteger)b;
+(UIColor*)R:(NSUInteger)r G:(NSUInteger)g B:(NSUInteger)b A:(CGFloat)a;

@end

@implementation UIColor (RGB)

+(UIColor*)R:(NSUInteger)r G:(NSUInteger)g B:(NSUInteger)b {
     return [self R:r G:g B:b A:1.0];
}

+(UIColor*)R:(NSUInteger)r G:(NSUInteger)g B:(NSUInteger)b A:(CGFloat)a {
    return [UIColor colorWithRed:((CGFloat)r)/255.0 green:((CGFloat)g)/255.0 blue:((CGFloat)b)/255.0 alpha:a];
}

@end

Since iOS 5, you can use UIColor's getRed(_:green:blue:alpha) method (here shown in Swift):

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

let color = UIColor.systemGreen
// getRed(_:green:blue:alpha) returns 'true' on successful conversion
if color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
{
    print("red: \(red)\ngreen: \(green)\nblue: \(blue)\nalpha: \(alpha)")
}

/*
which for `systemGreen` in light mode prints:
red: 0.20392156862745098
green: 0.7803921568627451
blue: 0.34901960784313724
alpha: 1.0
*/

and, as a computed property in an extension to UIColor:

extension UIColor {
    var rgbaComponents: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
        var red: CGFloat = 0
        var green: CGFloat = 0
        var blue: CGFloat = 0
        var alpha: CGFloat = 0

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

        return (red, green, blue, alpha)
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top