16进制颜色与UIColor互转_移动开发_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > 移动开发 > 16进制颜色与UIColor互转

16进制颜色与UIColor互转

 2014/12/2 19:11:10  粉粉色  程序员俱乐部  我要评论(0)
  • 摘要:效果图:代码:-(void)viewDidLoad{[superviewDidLoad];//Doanyadditionalsetupafterloadingtheview.UIView*view=[[UIViewalloc]initWithFrame:CGRectMake(50,100,200,200)];view.backgroundColor=[selfcolorWithHexString:@"e26562"];[self.viewaddSubview:view];
  • 标签:

效果图:

代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIView *view=[[UIView alloc]initWithFrame:CGRectMake(50, 100, 200, 200)];
    view.backgroundColor=[self colorWithHexString:@"e26562"];
    [self.view addSubview:view];
    
}
//16进制颜色#e26562与UIColor互转,设置View背景颜色
- (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];
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    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];
}

 

  • 相关文章
发表评论
用户名: 匿名