简体   繁体   中英

Objective C UIColor to NSString

I need to convert a UIColor to an NSString with the name of the color ie

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM