Reputation: 6560
So here are the colors I am trying to convert from UIColor to CGColor:
Here is the Blue vs. iOS's rendering:
a:
b:
Here is the Red vs. iOS's rendering: a b:
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?
Upvotes: 7
Views: 14170
Reputation: 8739
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)
}
}
Upvotes: 0
Reputation: 10195
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
Upvotes: 3
Reputation: 3077
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]
Upvotes: 25