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

转载于:https://www.cnblogs.com/pengyingh/articles/2451218.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值