在作iOS開發時,通常咱們會吸色,就是產品給的圖咱們通常會吸色,可是最近吸色時候,老大說有較大的顏色誤差,因此要求咱們直接使用UI給出的額16進制顏色,你也能夠搜索《RGB顏色值轉換成十六進制顏色碼:》先把16進制顏色轉換爲RGB的而後再寫,可是這樣有點影響開發速度,因此呢就寫了一個UIColor的分類,直接使用16進制的顏色。spa
UIColor的分類DLColorChange .h文件
#import <UIKit/UIKit.h> @interface UIColor (DLColorChange) // 顏色轉換:iOS中(以#開頭)十六進制的顏色轉換爲UIColor(RGB) + (UIColor *) colorWithHexString: (NSString *)color; @end
UIColor的分類DLColorChange .m文件
#import "UIColor+DLColorChange.h" @implementation UIColor (DLColorChange) + (UIColor *) colorWithHexString: (NSString *)color { NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString]; // String should be 6 or 8 characters if ([cString length] < 6) { return [UIColor clearColor]; } // 判斷前綴 if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2]; if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1]; if ([cString length] != 6) return [UIColor clearColor]; // 從六位數值中找到RGB對應的位數並轉換 NSRange range; range.location = 0; range.length = 2; //R、G、B NSString *rString = [cString substringWithRange:range]; range.location = 2; NSString *gString = [cString substringWithRange:range]; range.location = 4; NSString *bString = [cString substringWithRange:range]; // Scan values unsigned int r, g, b; [[NSScanner scannerWithString:rString] scanHexInt:&r]; [[NSScanner scannerWithString:gString] scanHexInt:&g]; [[NSScanner scannerWithString:bString] scanHexInt:&b]; return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f]; } @end
咱們能夠把code
#import "UIColor+DLColorChange.h"
寫在pch文件中,這樣咱們全局就能夠用。調用以下blog
self.view.backgroundColor=[UIColor colorWithHexString:@"#edae48"];