之前想自己写一个UIColor的分类,实现可以输入十六进制字符串
(例如:0xff8ac)
的颜色值来设置方便的设置颜色(虽然网上有很多,但是想自己造轮子嘛)
,但是关于十六进制和字符串之间的转换一直找不到简便的方法来实现,最近逼着自己看C语言基础及进阶的书,总算还是有点收获,所以第一时间来跟大家分享。
1、数字转十六进制字符串
- (NSString *)stringWithHexNumber:(NSUInteger)hexNumber{
char hexChar[6];
sprintf(hexChar, "%x", (int)hexNumber);
NSString *hexString = [NSString stringWithCString:hexChar encoding:NSUTF8StringEncoding];
return hexString;
}
解释一下,函数
sprintf
是C语言提供的格式化输出函数
,"%x"
相信大家都能看懂,就是十六进制输出,如果换成大写"%X"
,相应的字符串结果也会换成大写。因为是判断颜色值,所以字符数组固定6位,最后在最前面做一个判断,if(hexNumber > 0xffffff) return nil;
。不仅支持十六进制,还支持八进制输出"%o"
,当然意义不大。
2、十六进制字符串转数字
- (NSInteger)numberWithHexString:(NSString *)hexString{
const char *hexChar = [hexString cStringUsingEncoding:NSUTF8StringEncoding];
int hexNumber;
sscanf(hexChar, "%x", &hexNumber);
return (NSInteger)hexNumber;
}
sscanf
是C言语提供的格式化输入函数
,很简单,当然你要颜色值如果是0xabc123
格式的你就要自己先判定了。大家可以测试一下。
3、UIColor分类实现十六进制颜色值转换
.h文件
#import <UIKit/UIKit.h>
@interface UIColor (Hex)
/**
@param hexString NSString e.g:@"0xFC5B13"
@param alpha alhpa
*/
+ (instancetype)colorWithHexString:(NSString *)hexString alpha:(CGFloat)alpha;
+ (instancetype)colorWithHexString:(NSString *)hexString;
@end
.m文件
#import "UIColor+Hex.h"
@implementation UIColor (Hex)
+ (instancetype)colorWithHex:(int)hexNumber alpha:(CGFloat)alpha{
if (hexNumber > 0xFFFFFF) return nil;
CGFloat red = ((hexNumber >> 16) & 0xFF) / 255.0;
CGFloat green = ((hexNumber >> 8) & 0xFF) / 255.0;
CGFloat blue = (hexNumber & 0xFF) / 255.0;
UIColor *color = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
return color;
}
+ (instancetype)colorWithHexString:(NSString *)hexString alpha:(CGFloat)alpha{
hexString = [[hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
UIColor *defaultColor = [UIColor clearColor];
if (hexString.length < 6) return defaultColor;
if ([hexString hasPrefix:@"#"]) hexString = [hexString substringFromIndex:1];
if ([hexString hasPrefix:@"0X"]) hexString = [hexString substringFromIndex:2];
if (hexString.length != 6) return defaultColor;
//method1
NSScanner *scanner = [NSScanner scannerWithString:hexString];
unsigned int hexNumber;
if (![scanner scanHexInt:&hexNumber]) return defaultColor;
//method2
const char *char_str = [hexString cStringUsingEncoding:NSASCIIStringEncoding];
int hexNum;
sscanf(char_str, "%x", &hexNum);
return [UIColor colorWithHex:hexNumber alpha:alpha];
}
+ (instancetype)colorWithHexString:(NSString *)hexString{
return [UIColor colorWithHexString:hexString alpha:1.0f];
}
method1
是苹果官方提供的类,功能和method2
类似,选一种即可。