Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.87 KB | None | 0 0
  1. /// 参考 WeexSDK `WXConvert.m` 中的 `+UIColor:` 方法 (且在其基础上添加了对 #rrggbbaa 格式的支持)
  2. /// @param colorString 颜色字符串, 支持以下格式:
  3. /// #fff
  4. /// #rrggbb
  5. /// #rrggbbaa
  6. /// rgb(r,g,b)
  7. /// rgba(r,g,b,a)
  8. + (UIColor *)colorWithColorString:(NSString *)colorString {
  9. // 1. check cache
  10. static NSCache *colorCache;
  11. static dispatch_once_t onceToken;
  12. dispatch_once(&onceToken, ^{
  13. colorCache = [[NSCache alloc] init];
  14. colorCache.countLimit = 64;
  15. });
  16.  
  17. if ([colorString isKindOfClass:[NSNull class]] || !colorString) {
  18. return nil;
  19. }
  20.  
  21. UIColor *color = [colorCache objectForKey:colorString];
  22. if (color) {
  23. return color;
  24. }
  25.  
  26. // Default color is white
  27. double red = 255, green = 255, blue = 255, alpha = 1.0;
  28.  
  29. if([colorString isKindOfClass:[NSString class]]){
  30.  
  31. /* `WXConvert.m` 中的 knownColors 相关功能用不上, 已删除*/
  32.  
  33. NSString *rgba = colorString;
  34.  
  35. if ([rgba hasPrefix:@"#"]) {
  36. // #fff
  37. if ([rgba length] == 4) {
  38. unichar f = [rgba characterAtIndex:1];
  39. unichar s = [rgba characterAtIndex:2];
  40. unichar t = [rgba characterAtIndex:3];
  41. rgba = [NSString stringWithFormat:@"#%C%C%C%C%C%C", f, f, s, s, t, t];
  42. }
  43.  
  44. uint32_t colorValue = 0;
  45. sscanf(rgba.UTF8String, "#%x", &colorValue);
  46.  
  47. if ([rgba length] == 7) {
  48. // #rrggbb
  49. red = ((colorValue & 0xFF0000) >> 16) / 255.0;
  50. green = ((colorValue & 0x00FF00) >> 8) / 255.0;
  51. blue = (colorValue & 0x0000FF) / 255.0;
  52. } else if ([rgba length] == 9) {
  53. // #rrggbbaa
  54. red = ((colorValue & 0xFF000000) >> 24) / 255.0;
  55. green = ((colorValue & 0x00FF0000) >> 16) / 255.0;
  56. blue = ((colorValue & 0x0000FF00) >> 8) / 255.0;
  57. alpha = (colorValue & 0x000000FF) / 255.0;
  58. }
  59.  
  60. } else if ([rgba hasPrefix:@"rgb("]) {
  61. // rgb(r,g,b)
  62. int r,g,b;
  63. sscanf(rgba.UTF8String, "rgb(%d,%d,%d)", &r, &g, &b);
  64. red = r / 255.0;
  65. green = g / 255.0;
  66. blue = b / 255.0;
  67. } else if ([rgba hasPrefix:@"rgba("]) {
  68. // rgba(r,g,b,a)
  69. int r,g,b;
  70. sscanf(rgba.UTF8String, "rgba(%d,%d,%d,%lf)", &r, &g, &b, &alpha);
  71. red = r / 255.0;
  72. green = g / 255.0;
  73. blue = b / 255.0;
  74. }
  75. }
  76.  
  77. color = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
  78. // 6. cache color
  79. if (color && colorString) {
  80. [colorCache setObject:color forKey:colorString];
  81. }
  82.  
  83. return color;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement