这取决于是否有“私有”颜色格式的自由。一些颜色不适合要求 RGBA(这就是为什么 get...
方法返回一个 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