首页 > 代码库 > 使用十六进制色值表示UIColor

使用十六进制色值表示UIColor

假如你有一个值为 @”0A5CEA” (字符串类型的16进制色值) ,可以如下方法创建UIColor对象:

UIColor *color = [UIColor colorwithHexString:@"0A5CEA" alpha:.9];

 

UIColor Category

然后我们来创建一个UIColor Category,

声明代码 UIColor+fromHex.h :

@interface UIColor (fromHex)+ (UIColor *)colorwithHexString:(NSString *)hexStr alpha:(CGFloat)alpha;@end

implementation代码 UIColor+fromHex.m :

 1 @implementation UIColor (fromHex) 2   3 + (UIColor *)colorwithHexString:(NSString *)hexStr alpha:(CGFloat)alpha; 4 { 5   //----------------------------------------- 6   // Convert hex string to an integer 7   //----------------------------------------- 8   unsigned int hexint = 0; 9  10   // Create scanner11   NSScanner *scanner = [NSScanner scannerWithString:hexStr];12  13   // Tell scanner to skip the # character14   [scanner setCharactersToBeSkipped:[NSCharacterSet 15     characterSetWithCharactersInString:@"#"]];16   [scanner scanHexInt:&hexint];17  18   //-----------------------------------------19   // Create color object, specifying alpha20   //-----------------------------------------21   UIColor *color =22     [UIColor colorWithRed:((CGFloat) ((hexint & 0xFF0000) >> 16))/25523     green:((CGFloat) ((hexint & 0xFF00) >> 8))/25524     blue:((CGFloat) (hexint & 0xFF))/25525     alpha:alpha];26  27   return color;28 }29  30 @end

第8-15行 对 hex value 转换为 unsigned integer.

第20-24行 创建一个 UIColor object 通过位操作 ‘&’ 计算各RGB颜色值, 同时除以255得到float值。

下面示例代码, 包括十六进制值格式“0x0A5CEA” 和@”#0A5CEA” (后者一般用于web开发):

 1 NSString *hexStr1 = @"123ABC"; 2 NSString *hexStr2 = @"#123ABC"; 3 NSString *hexStr3 = @"0x123ABC"; 4   5 UIColor *color1 = [UIColor colorwithHexString:hexStr1 alpha:.9]; 6 NSLog(@"UIColor: %@", color1); 7   8 UIColor *color2 = [UIColor colorwithHexString:hexStr2 alpha:.9]; 9 NSLog(@"UIColor: %@", color2);10  11 UIColor *color3 = [UIColor colorwithHexString:hexStr3 alpha:.9];12 NSLog(@"UIColor: %@", color3);

 

结果如下:

UIColor: UIDeviceRGBColorSpace 0.0705882 0.227451 0.737255 0.9UIColor: UIDeviceRGBColorSpace 0.0705882 0.227451 0.737255 0.9UIColor: UIDeviceRGBColorSpace 0.0705882 0.227451 0.737255 0.9