UIColor+Hex.m 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. //
  2. // UIColor+Hex.m
  3. // luftemed
  4. //
  5. // Created by 林柏显 on 16/11/8.
  6. // Copyright © 2016年 林柏显. All rights reserved.
  7. //
  8. #import "UIColor+Hex.h"
  9. @implementation UIColor (Hex)
  10. + (UIColor *)colorWithHexString:(NSString *)hexColorString {
  11. if ([hexColorString length] < 6) { // 长度不合法
  12. return [UIColor blackColor];
  13. }
  14. NSString *tempString = [hexColorString lowercaseString];
  15. if ([tempString hasPrefix:@"0x"]) { // 检查开头是 0x
  16. tempString = [tempString substringFromIndex:2];
  17. } else if ([tempString hasPrefix:@"#"]) { // 检查开头是#
  18. tempString = [tempString substringFromIndex:1];
  19. }
  20. if ([tempString length] != 6) {
  21. return [UIColor blackColor];
  22. }
  23. // 分解三种颜色的值
  24. NSRange range = NSMakeRange(0, 2);
  25. NSString *rString = [tempString substringWithRange:range];
  26. range.location = 2;
  27. NSString *gString = [tempString substringWithRange:range];
  28. range.location = 4;
  29. NSString *bString = [tempString substringWithRange:range];
  30. // 取三种颜色值
  31. unsigned int r, g, b;
  32. [[NSScanner scannerWithString:rString] scanHexInt:&r];
  33. [[NSScanner scannerWithString:gString] scanHexInt:&g];
  34. [[NSScanner scannerWithString:bString] scanHexInt:&b];
  35. return [UIColor colorWithRed:((float)r / 255.0f)
  36. green:((float)g / 255.0f)
  37. blue:((float)b / 255.0f)
  38. alpha:1.0f];
  39. }
  40. @end