首页 > 其他 > 详细

颜色转换到16进制

时间:2016-03-28 15:04:56      阅读:232      评论:0      收藏:0      [点我收藏+]

#import <UIKit/UIKit.h>

 

@interface UIColor (Addition)

 

+ (UIColor *)getColorWithHexString:(NSString *)hexColorStr;

 

@end

 

#import "UIColor+Addition.h"

 

@implementation UIColor (Addition)

 

#pragma mark -- 颜色转换

+ (UIColor *)getColorWithHexString:(NSString *)hexColorStr

{

    NSString *cString = [[hexColorStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];

    

    // String should be 6 or 8 characters

    if ([cString length] < 6) return nil;

    

    // 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 nil;

    // Separate into r, g, b substrings

    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];

    

    // 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

 

颜色转换到16进制

原文:http://www.cnblogs.com/dcy123/p/5328968.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!