zoukankan      html  css  js  c++  java
  • iOS开发-16进制颜色转换

    项目中经常会用到颜色转换,有的是通过十六进制转成数字转颜色,想简单的点直接通过字符串转一下,简单扩展了一下分类UIColor,代码如下:

    +(UIColor *)colorWithHex:(NSString *)hexColor{
        return [self colorWithHex:hexColor alpha:1.0f];
    }
    //http://www.cnblogs.com/xiaofeixiang  iOS技术交流:228407086
    +(UIColor *)colorWithHex:(NSString *)hexColor alpha:(float)alpha{
        //删除空格
        NSString *colorStr = [[hexColor stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
        // String should be 6 or 8 characters
        if ([colorStr length] < 6||[colorStr length]>7)
        {
            return [UIColor clearColor];
        }
        //
        if ([colorStr hasPrefix:@"#"])
        {
            colorStr = [colorStr substringFromIndex:1];
        }
    
        NSRange range;
        range.location = 0;
        range.length = 2;
        //red
        NSString *redString = [colorStr substringWithRange:range];
        //green
        range.location = 2;
        NSString *greenString = [colorStr substringWithRange:range];
        //blue
        range.location = 4;
        NSString *blueString= [colorStr substringWithRange:range];
        
        // Scan values
        unsigned int red, green, blue;
        [[NSScanner scannerWithString:redString] scanHexInt:&red];
        [[NSScanner scannerWithString:greenString] scanHexInt:&green];
        [[NSScanner scannerWithString:blueString] scanHexInt:&blue];
        return [UIColor colorWithRed:((float)red/ 255.0f) green:((float)green/ 255.0f) blue:((float)blue/ 255.0f) alpha:alpha];
    }
  • 相关阅读:
    SQL SERVER 2005 行转列
    为什么jQuery.get、jQuery.getJSON、jQuery.post无法返回JSON
    Silverlight 布局控件
    python socket connection
    linux下缓存的查看/修改
    openstackflat 网络问题
    Fail to start neutronserver
    copy module
    python ConfigParser
    itertools 介绍
  • 原文地址:https://www.cnblogs.com/xiaofeixiang/p/4621523.html
Copyright © 2011-2022 走看看