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 }