UIColor到无符号整数

tGi*_*ani 2 iphone ios

我在这里找到了一个UIImage替换颜色的类别

问题是方法签名接收无符号整数颜色代码:

- (UIImage *)imageByRemovingColorsWithMinColor:(uint)minColor maxColor:(uint)maxColor
Run Code Online (Sandbox Code Playgroud)

如何从UIColor?获得正确的无符号整数值?

我其实想要用紫色代替黑色.

小智 7

如果您查看了源代码,您会发现它们使用此无符号整数值作为十六进制颜色代码,其中

colorcode = ((unsigned)(red * 255) << 16) + ((unsigned)(green * 255) << 8) + ((unsigned)(blue * 255) << 0)
Run Code Online (Sandbox Code Playgroud)

所以你可以使用这样的方法从UIColor对象获得这样的十六进制值:

@implementation UIColor (Hex)

- (NSUInteger)colorCode
{
    float red, green, blue;
    if ([self getRed:&red green:&green blue:&blue alpha:NULL])
    {
        NSUInteger redInt = (NSUInteger)(red * 255 + 0.5);
        NSUInteger greenInt = (NSUInteger)(green * 255 + 0.5);
        NSUInteger blueInt = (NSUInteger)(blue * 255 + 0.5);

        return (redInt << 16) | (greenInt << 8) | blueInt;
    }

    return 0;
}

@end
Run Code Online (Sandbox Code Playgroud)

然后使用它像:

NSUInteger hexPurple = [[UIColor purpleColor] colorCode];
Run Code Online (Sandbox Code Playgroud)

  • 请注意,这不适用于64位iOS.将更改浮动修复为CGFloat.尝试编辑答案但被拒绝了. (2认同)