UIColor+AS.m 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. //
  2. // UIColor+AS.m
  3. // Asteria
  4. //
  5. // Created by iOS on 2023/4/25.
  6. //
  7. #import "UIColor+AS.h"
  8. @implementation UIColor (AS)
  9. + (UIColor *)colorWithHexString:(NSString *)color {
  10. return [self colorWithHexString:color Alpha:1.0f];
  11. }
  12. + (UIColor *)colorWithHexString:(NSString *)color Alpha:(CGFloat)alpha {
  13. NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
  14. if ([cString length] < 6) {
  15. return [UIColor clearColor];
  16. }
  17. //判断前缀
  18. if ([cString hasPrefix:@"0X"]) {
  19. cString = [cString substringFromIndex:2];
  20. }
  21. if ([cString hasPrefix:@"#"]) {
  22. cString = [cString substringFromIndex:1];
  23. }
  24. if ([cString length] != 6) {
  25. return [UIColor clearColor];
  26. }
  27. //从六位数值中找到RGB对应的位数并转换
  28. NSRange range;
  29. range.location = 0;
  30. range.length = 2;
  31. //R G B
  32. NSString *rString = [cString substringWithRange:range];
  33. range.location = 2;
  34. NSString *gString = [cString substringWithRange:range];
  35. range.location = 4;
  36. NSString *bString = [cString substringWithRange:range];
  37. unsigned int r, g, b;
  38. [[NSScanner scannerWithString:rString] scanHexInt:&r];
  39. [[NSScanner scannerWithString:gString] scanHexInt:&g];
  40. [[NSScanner scannerWithString:bString] scanHexInt:&b];
  41. return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:alpha];
  42. }
  43. @end