将16进制颜色转换成RGB值

1.16进制颜色转换成UIColor

很多地方我们都使用16进制颜色,但iPhone使用的是UIColor对象,不直接支持16进制颜色,为此,需要我们手动将16进制颜色转换为UIColor

  • - (UIColor *)getColor:(NSString *)hexColor
  • {
  •     unsigned int red,green,blue;
  •     NSRange range;
  •     range.length = 2;
  •     
  •     range.location = 0;
  •     [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:>red];
  •     
  •     range.location = 2;
  •     [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:>green];
  •     
  •     range.location = 4;
  •     [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:>blue];
  •     
  •     return [UIColor colorWithRed:(float)(red/255.0f) green:(float)(green / 255.0f) blue:(float)(blue / 255.0f) alpha:1.0f];
  • }
  •  
  • [self.view setBackgroundColor:[self getColor:@"FF0000"]];


2. 16进制颜色值转换到RGB值(cocos2d-iPhone版)

1 + (ccColor3B)colorWithHexString: (NSString *) stringToConvert

2 { 

3 //去掉前后空格换行符 

4 NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString]; 

5 

6 if ([cString length] < 6

7 return ccWHITE; 

8 

9 if ([cString hasPrefix:@"0X"]) 

10 cString = [cString substringFromIndex:2]; 

11 else if ([cString hasPrefix:@"#"]) 

12 cString = [cString substringFromIndex:1]; 

13 

14 if ([cString length] != 6

15 return ccWHITE; 

16 

17 // Separate into r, g, b substrings 

18 NSRange range; 

19 range.location = 0

20 range.length = 2

21 NSString *rString = [cString substringWithRange:range]; 

22 

23 range.location = 2

24 NSString *gString = [cString substringWithRange:range]; 

25

26 range.location = 4

27 NSString *bString = [cString substringWithRange:range]; 

28

29 unsigned int r, g, b; 

30 [[NSScanner scannerWithString:rString] scanHexInt:&r]; 

31 [[NSScanner scannerWithString:gString] scanHexInt:&g]; 

32 [[NSScanner scannerWithString:bString] scanHexInt:&b]; 

33 //NSLog(@"r = %u, g = %u, b = %u",r, g, b); 

34 return ccc3(r, g, b); 

35 }

你可能感兴趣的:(将16进制颜色转换成RGB值)