i have a problem in converting uicolor to hex color, here what i found
CGColorRef colorref = [[Colorview_ backgroundColor] CGColor];
int numComponents = CG
I tried that yesterday because I had to get a hex color from a uicolor and made it work in javascript too, but this doesn't work when a component is 0, because it gets a 0 instead of a 00. So a pure cyan would be RGB 0 255 255, and this code would return #0ffff instead of #00ffff.
I made this code from yours, and it's working on my app:
-(NSString*)colorToHex:(UIColor*)color{
CGColorRef colorref = [color CGColor];
const CGFloat *components = CGColorGetComponents(colorref);
NSString *hexString = @"#";
int hexValue = 0;
for (int i=0; i<3; i++) {
if (components[i] == 0) {
hexString = [NSString stringWithFormat:@"%@00", hexString];
}else{
hexValue = 0xFF*components[i];
hexString = [NSString stringWithFormat:@"%@%x", hexString, hexValue];
}
}
return hexString;
}
NSString *hexString = [NSString stringWithFormat:@"#%d", hexValue];
You are formatting it as a digit with %d
You want to format it as hex with %x or %X -- maybe as string %s I didnt check what the function is doing and what int hexValue
is holding
d or i Signed decimal integer 392
x Unsigned hexadecimal integer 7fa
X Unsigned hexadecimal integer (capital letters) 7FA
The sylphos answer above doesnt work for darkGrayColor.
This works better (taken from http://softteco.blogspot.jp/2011/06/extract-hex-rgb-color-from-uicolor.html):
- (NSString *) hexFromUIColor:(UIColor *)color {
if (CGColorGetNumberOfComponents(color.CGColor) < 4) {
const CGFloat *components = CGColorGetComponents(color.CGColor);
color = [UIColor colorWithRed:components[0] green:components[0] blue:components[0] alpha:components[1]];
}
if (CGColorSpaceGetModel(CGColorGetColorSpace(color.CGColor)) != kCGColorSpaceModelRGB) {
return [NSString stringWithFormat:@"#FFFFFF"];
}
return [NSString stringWithFormat:@"#%02X%02X%02X", (int)((CGColorGetComponents(color.CGColor))[0]*255.0), (int)((CGColorGetComponents(color.CGColor))[1]*255.0), (int)((CGColorGetComponents(color.CGColor))[2]*255.0)];
}
Here is a version of this, but formatted as a C function:
static inline NSString *hexFromUIColor(UIColor * _color) {
if (CGColorGetNumberOfComponents(_color.CGColor) < 4) {
const CGFloat *components = CGColorGetComponents(_color.CGColor);
_color = [UIColor colorWithRed:components[0] green:components[0] blue:components[0] alpha:components[1]];
}
if (CGColorSpaceGetModel(CGColorGetColorSpace(_color.CGColor)) != kCGColorSpaceModelRGB) {
return [NSString stringWithFormat:@"#FFFFFF"];
}
return [NSString stringWithFormat:@"#%02X%02X%02X", (int)((CGColorGetComponents(_color.CGColor))[0]*255.0), (int)((CGColorGetComponents(_color.CGColor))[1]*255.0), (int)((CGColorGetComponents(_color.CGColor))[2]*255.0)];
}