I need to convert a UIColor to an NSString with the name of the color i.e.
[UIColor redColor];
should become
@"RedColor"
I've already tried[UIColor redColor].CIColor.stringRepresentation
but it causes a compiler error
Just expanding on the answer that @Luke linked to which creates a CGColorRef to pass to CIColor:
CGColorRef colorRef = [UIColor grayColor].CGColor;
You could instead simply pass the CGColor property of the UIColor you're working on like:
NSString *colorString = [[CIColor colorWithCGColor:[[UIColor redColor] CGColor]] stringRepresentation];
Don't forget to import the Core Image framework.
Side note, a quick and easy way to convert back to a UIColor from the string could be something like this:
NSArray *parts = [colorString componentsSeparatedByString:@" "];
UIColor *colorFromString = [UIColor colorWithRed:[parts[0] floatValue] green:[parts[1] floatValue] blue:[parts[2] floatValue] alpha:[parts[3] floatValue]];
This is the shortest way to convert UIColor to NSString:
- (NSString *)stringFromColor:(UIColor *)color
{
const size_t totalComponents = CGColorGetNumberOfComponents(color.CGColor);
const CGFloat * components = CGColorGetComponents(color.CGColor);
return [NSString stringWithFormat:@"#%02X%02X%02X",
(int)(255 * components[MIN(0,totalComponents-2)]),
(int)(255 * components[MIN(1,totalComponents-2)]),
(int)(255 * components[MIN(2,totalComponents-2)])];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With