iOS开发-从16进制颜色中获取UIColor

Changwei | 1/28/2015 6:24:00 PM


目前iOS中设置UIColor只能使用其枚举值、RGB等方法,不能直接将常用的16进制颜色值直接转为UIColor对象,所以写了点代码,将16进制颜色值转为UIColor。

代码如下,

//头文件
#import
<Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface TextServcie : NSObject +(UIColor *) getColorFromHEX:(NSString *)hex; @end

.m

@implementation TextServcie

+(UIColor *)getcolorfromHEX:(NSString *)hex{

    hex= [[hex uppercaseString] substringFromIndex:1];

    CGFloat valueArray[3];

    NSArray *strArray=[NSArray arrayWithObjects:[hex substringWithRange:NSMakeRange(0, 2)],[hex substringWithRange:NSMakeRange(2, 2)],[hex substringWithRange:NSMakeRange(4, 2)] ,nil];

    for( int i=0;i<strArray.count;i++){

        hex=strArray[i];

        CGFloat value=([hex characterAtIndex:0]>'9'?[hex characterAtIndex:0]-'A'+10:[hex characterAtIndex:0]-'0')*16.0f+([hex characterAtIndex:1]>'9'?[hex characterAtIndex:1]-'A'+10:[hex characterAtIndex:1]-'0');

        valueArray[i]=value;

    }

    return [UIColor colorWithRed:valueArray[0]/255 green:valueArray[1]/255 blue:valueArray[2]/255 alpha:1];

}

@end

以上代码,工作正常,下次不用再用工具手动转RGB了

 

Github地址:https://github.com/ChangweiZhang/HexColorService