Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// 参考 WeexSDK `WXConvert.m` 中的 `+UIColor:` 方法 (且在其基础上添加了对 #rrggbbaa 格式的支持)
- /// @param colorString 颜色字符串, 支持以下格式:
- /// #fff
- /// #rrggbb
- /// #rrggbbaa
- /// rgb(r,g,b)
- /// rgba(r,g,b,a)
- + (UIColor *)colorWithColorString:(NSString *)colorString {
- // 1. check cache
- static NSCache *colorCache;
- static dispatch_once_t onceToken;
- dispatch_once(&onceToken, ^{
- colorCache = [[NSCache alloc] init];
- colorCache.countLimit = 64;
- });
- if ([colorString isKindOfClass:[NSNull class]] || !colorString) {
- return nil;
- }
- UIColor *color = [colorCache objectForKey:colorString];
- if (color) {
- return color;
- }
- // Default color is white
- double red = 255, green = 255, blue = 255, alpha = 1.0;
- if([colorString isKindOfClass:[NSString class]]){
- /* `WXConvert.m` 中的 knownColors 相关功能用不上, 已删除*/
- NSString *rgba = colorString;
- if ([rgba hasPrefix:@"#"]) {
- // #fff
- if ([rgba length] == 4) {
- unichar f = [rgba characterAtIndex:1];
- unichar s = [rgba characterAtIndex:2];
- unichar t = [rgba characterAtIndex:3];
- rgba = [NSString stringWithFormat:@"#%C%C%C%C%C%C", f, f, s, s, t, t];
- }
- uint32_t colorValue = 0;
- sscanf(rgba.UTF8String, "#%x", &colorValue);
- if ([rgba length] == 7) {
- // #rrggbb
- red = ((colorValue & 0xFF0000) >> 16) / 255.0;
- green = ((colorValue & 0x00FF00) >> 8) / 255.0;
- blue = (colorValue & 0x0000FF) / 255.0;
- } else if ([rgba length] == 9) {
- // #rrggbbaa
- red = ((colorValue & 0xFF000000) >> 24) / 255.0;
- green = ((colorValue & 0x00FF0000) >> 16) / 255.0;
- blue = ((colorValue & 0x0000FF00) >> 8) / 255.0;
- alpha = (colorValue & 0x000000FF) / 255.0;
- }
- } else if ([rgba hasPrefix:@"rgb("]) {
- // rgb(r,g,b)
- int r,g,b;
- sscanf(rgba.UTF8String, "rgb(%d,%d,%d)", &r, &g, &b);
- red = r / 255.0;
- green = g / 255.0;
- blue = b / 255.0;
- } else if ([rgba hasPrefix:@"rgba("]) {
- // rgba(r,g,b,a)
- int r,g,b;
- sscanf(rgba.UTF8String, "rgba(%d,%d,%d,%lf)", &r, &g, &b, &alpha);
- red = r / 255.0;
- green = g / 255.0;
- blue = b / 255.0;
- }
- }
- color = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
- // 6. cache color
- if (color && colorString) {
- [colorCache setObject:color forKey:colorString];
- }
- return color;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement