码迷,mamicode.com
首页 > 移动开发 > 详细

[iOS]把16进制颜色转换UIColor

时间:2015-08-26 13:58:48      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:uicolor

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    


    UIColor *color = [self colorWithHexString:@"#81c52b"];

    [self.view setBackgroundColor:color];

}


- (UIColor *) colorWithHexString: (NSString *) stringToConvert

{

    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];//字符串处理

    //例子,stringToConvert #ffffff

    if ([cString length] < 6)

        return [UIColor redColor];//如果非十六进制,返回白色

    if ([cString hasPrefix:@"#"])

        cString = [cString substringFromIndex:1];//去掉头

    if ([cString length] != 6)//去头非十六进制,返回白色

        return [UIColor greenColor];

    //分别取RGB的值

    NSRange range;

    range.location = 0;

    range.length = 2;

    NSString *rString = [cString substringWithRange:range];

    

    range.location = 2;

    NSString *gString = [cString substringWithRange:range];

    

    range.location = 4;

    NSString *bString = [cString substringWithRange:range];

    

    unsigned int r, g, b;

    //NSScanner把扫描出的制定的字符串转换成Int类型

    [[NSScanner scannerWithString:rString] scanHexInt:&r];

    [[NSScanner scannerWithString:gString] scanHexInt:&g];

    [[NSScanner scannerWithString:bString] scanHexInt:&b];

    //转换为UIColor

    return [UIColor colorWithRed:((float) r / 255.0f)

                           green:((float) g / 255.0f)

                            blue:((float) b / 255.0f)

                           alpha:1.0f];

}

版权声明:本文为博主原创文章,未经博主允许不得转载。

[iOS]把16进制颜色转换UIColor

标签:uicolor

原文地址:http://blog.csdn.net/s133315202/article/details/48002017

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!