这取决于颜色的“私有”格式的自由度。有些颜色对被要求输入 RGBA 反应不佳(因此这些get...
方法为什么返回 a BOOL
——它们并不总是成功),所以这个实现包括颜色类型和值。
@implementation UIColor (JSON)
- (NSString *)json_stringValue
{
CGFloat r, g, b, a, h, s, w;
if ([self getRed:&r green:&g blue:&b alpha:&a])
return [NSString stringWithFormat:@"rgba:%f,%f,%f,%f", r,g,b,a];
else if ([self getHue:&h saturation:&s brightness:&b alpha:&a])
return [NSString stringWithFormat:@"hsba:%f,%f,%f,%f", h,s,b,a];
else if ([self getWhite:&w alpha:&a])
return [NSString stringWithFormat:@"wa:%f,%f", w, a];
NSLog(@"WARNING: unable to serialize color %@", self);
return nil;
}
@end
@implementation NSString (JSON)
- (UIColor *)json_color
{
NSArray *comps = [self componentsSeparatedByString:@":"];
NSArray *colors = [comps[1] componentsSeparatedByString:@","];
NSUInteger count = colors.count;
CGFloat values[4] = {0,0,0,0};
for (NSUInteger i = 0; i < count; i++) values[i] = [colors[i] floatValue];
if ([comps[0] isEqualToString:@"rgba"])
return [UIColor colorWithRed:values[0] green:values[1] blue:values[2] alpha:values[3]];
else if ([comps[0] isEqualToString:@"hsba"])
return [UIColor colorWithHue:values[0] saturation:values[1] brightness:values[2] alpha:values[3]];
else if ([comps[0] isEqualToString:@"wa"])
return [UIColor colorWithWhite:values[0] alpha:values[1]];
NSLog(@"WARNING: unable to deserialize color %@", self);
return nil;
}
@end