Fork me on GitHub

cocoa中颜色的几种表示形式的转换

http://www.goodldy.com/2011/08/cocoa-color/

 

最近频繁用到颜色,整理了以下几个函数用于
NSColor,16进制,整形间的转换

@interface NSColor(NSColorHexadecimalValue)
-(NSString*)hexadecimalValueOfAnNSColor;
-(unsigned int)hexadecimalINTValueOfAnNSColor;
+(NSColor *)getColorFromhexStr:(NSString *)hexColor;
@end
 
@implementation NSColor(NSColorHexadecimalValue)
 
//NSColor 转为整形表示 和  16 进制字符串
-(unsigned int)hexadecimalINTValueOfAnNSColor
{
    NSString *tempStr=[self hexadecimalValueOfAnNSColor];
    if (tempStr)
    {
        unsigned int tempInt = 0;
        NSScanner *scanner = [NSScanner scannerWithString: tempStr];
        [scanner scanHexInt: &tempInt];
        return tempInt;
    }
    else
        return 0;
}
//NSColor 转为 16 进制字符串
-(NSString*)hexadecimalValueOfAnNSColor
{
    float redFloatValue, greenFloatValue, blueFloatValue;
    int redIntValue, greenIntValue, blueIntValue;
    NSString *redHexValue, *greenHexValue, *blueHexValue;
 
    NSColor *convertedColor=[self colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
 
    if(convertedColor)
    {
        [convertedColor getRed:&redFloatValue green:&greenFloatValue blue:&blueFloatValue alpha:NULL];
 
        redIntValue=redFloatValue*255.99999f;
        greenIntValue=greenFloatValue*255.99999f;
        blueIntValue=blueFloatValue*255.99999f;
 
        redHexValue=[NSString stringWithFormat:@"%02x", redIntValue];
        greenHexValue=[NSString stringWithFormat:@"%02x", greenIntValue];
        blueHexValue=[NSString stringWithFormat:@"%02x", blueIntValue];
 
        return=[NSString stringWithFormat:@"%@%@%@", redHexValue, greenHexValue, blueHexValue];
 
    }
    return nil;
 
}
 
//16 进制字符串  转成 NSColor
+(NSColor *)getColorFromhexStr:(NSString *)hexColor
{
    unsigned int red, green, blue,alpha;
    NSRange range;
    range.length = 2;
    range.location = 0;
 
    if ([hexColor length]==6)
        alpha = 255;
    else if ([hexColor length]==8)
    {
        [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&alpha];
        range.location+=2;
    }
    else
        return nil;     
 
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&red];
    range.location += 2;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&green];
    range.location += 2;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&blue];    
 
    return [NSColor colorWithDeviceRed:(float)(red/255.0f) green:(float)(green/255.0f)  blue:(float)(blue/255.0f) alpha:(float)(alpha/255.0f) ];
}
 
@end

posted on 2012-04-16 09:45  pengyingh  阅读(663)  评论(0编辑  收藏  举报

导航