如何根据iPhone(iOS)中的RGB值获取十六进制代码

A f*_*pha 2 cocoa-touch uicolor ios

我有RGBA(红色,绿色,蓝色,Alpha)的值.我知道我们可以通过使用获得基于这些东西的UIColor值

UIColor *currentColor = [UIColor colorWithRed: 1 green:1 blue:0 alpha:1];

但有没有办法可以使用iOS中的RGBA值直接获取颜色的Hex代码字符串.

Kri*_*dra 8

我不认为你可以直接从UIColor对象获取十六进制字符串.您需要从UIColor对象获取红色,绿色和蓝色组件并将它们转换为十六进制并追加.

你总是可以创造这样的东西

-(NSString *) UIColorToHexString:(UIColor *)uiColor{
    CGColorRef color = [uiColor CGColor];

    int numComponents = CGColorGetNumberOfComponents(color);
    int red,green,blue, alpha;
    const CGFloat *components = CGColorGetComponents(color);
    if (numComponents == 4){
        red =  (int)(components[0] * 255.0) ;
        green = (int)(components[1] * 255.0);
        blue = (int)(components[2] * 255.0);
        alpha = (int)(components[3] * 255.0);
    }else{
        red  =  (int)(components[0] * 255.0) ;
        green  =  (int)(components[0] * 255.0) ;
        blue  =  (int)(components[0] * 255.0) ;
        alpha = (int)(components[1] * 255.0);
    }

    NSString *hexString  = [NSString stringWithFormat:@"#%02x%02x%02x%02x",
                            alpha,red,green,blue];
    return hexString;
}
Run Code Online (Sandbox Code Playgroud)

编辑:在iOS 5.0中,您可以很容易地获得红色,绿色,蓝色组件

CGFloat red,green,blue,alpha;
[uicolor getRed:&red green:&green blue:&blue alpha:&alpha]
Run Code Online (Sandbox Code Playgroud)

所以上面的功能可以改为

-(NSString *) UIColorToHexString:(UIColor *)uiColor{
    CGFloat red,green,blue,alpha;
    [uiColor getRed:&red green:&green blue:&blue alpha:&alpha]

    NSString *hexString  = [NSString stringWithFormat:@"#%02x%02x%02x%02x",
                            ((int)alpha),((int)red),((int)green),((int)blue)];
    return hexString;
}
Run Code Online (Sandbox Code Playgroud)

  • @Krishnabhadra你的iOS 5快捷方式将失败,因为你在CGFloat目标上使用%x格式字符串(需要一个整数)(float或double).您仍然需要将元素转换为int. (2认同)