之前想自己寫一個(gè)UIColor的分類负懦,實(shí)現(xiàn)可以輸入十六進(jìn)制字符串
(例如:0xff8ac)
的顏色值來設(shè)置方便的設(shè)置顏色(雖然網(wǎng)上有很多畏铆,但是想自己造輪子嘛)
雷袋,但是關(guān)于十六進(jìn)制和字符串之間的轉(zhuǎn)換一直找不到簡便的方法來實(shí)現(xiàn),最近逼著自己看C語言基礎(chǔ)及進(jìn)階的書辞居,總算還是有點(diǎn)收獲楷怒,所以第一時(shí)間來跟大家分享。
1瓦灶、數(shù)字轉(zhuǎn)十六進(jìn)制字符串
- (NSString *)stringWithHexNumber:(NSUInteger)hexNumber{
char hexChar[6];
sprintf(hexChar, "%x", (int)hexNumber);
NSString *hexString = [NSString stringWithCString:hexChar encoding:NSUTF8StringEncoding];
return hexString;
}
解釋一下鸠删,函數(shù)
sprintf
是C語言提供的格式化輸出函數(shù)
,"%x"
相信大家都能看懂贼陶,就是十六進(jìn)制輸出刃泡,如果換成大寫"%X"
,相應(yīng)的字符串結(jié)果也會(huì)換成大寫碉怔。因?yàn)槭桥袛囝伾岛嫣宰址麛?shù)組固定6位,最后在最前面做一個(gè)判斷撮胧,if(hexNumber > 0xffffff) return nil;
桨踪。不僅支持十六進(jìn)制,還支持八進(jìn)制輸出"%o"
芹啥,當(dāng)然意義不大锻离。
2、十六進(jìn)制字符串轉(zhuǎn)數(shù)字
- (NSInteger)numberWithHexString:(NSString *)hexString{
const char *hexChar = [hexString cStringUsingEncoding:NSUTF8StringEncoding];
int hexNumber;
sscanf(hexChar, "%x", &hexNumber);
return (NSInteger)hexNumber;
}
sscanf
是C言語提供的格式化輸入函數(shù)
墓怀,很簡單汽纠,當(dāng)然你要顏色值如果是0xabc123
格式的你就要自己先判定了。大家可以測試一下傀履。
3虱朵、UIColor分類實(shí)現(xiàn)十六進(jìn)制顏色值轉(zhuǎn)換
.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
類似钓账,選一種即可碴犬。