Alex
Alex

Reputation: 1448

Objective C UIColor to NSString

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

Upvotes: 5

Views: 5452

Answers (2)

k06a
k06a

Reputation: 18745

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

Upvotes: 2

Mick MacCallum
Mick MacCallum

Reputation: 130183

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]];

Upvotes: 9

Related Questions