Get RGB value from UIColor presets

后端 未结 5 1935
日久生厌
日久生厌 2020-11-28 07:22

I my application I pass RGB color value to server. My app uses UIColor predefined values, like [UIColor grayColor], [UIColor redColor]. I know that I can use following code:

5条回答
  •  旧时难觅i
    2020-11-28 08:19

    Adding to Jesse's answer, here is how to preserve alpha:

    - (void)getRGBAComponents:(CGFloat [4])components forColor:(UIColor *)color {
        CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
        unsigned char resultingPixel[4] = {0};
        CGContextRef context = CGBitmapContextCreate(&resultingPixel,
                                                     1,
                                                     1,
                                                     8,
                                                     4,
                                                     rgbColorSpace,
                                                     kCGImageAlphaPremultipliedLast);
        CGContextSetFillColorWithColor(context, [color CGColor]);
        CGContextFillRect(context, CGRectMake(0, 0, 1, 1));
        CGContextRelease(context);
        CGColorSpaceRelease(rgbColorSpace);
    
        CGFloat a = resultingPixel[3] / 255.0;
        CGFloat unpremultiply = (a != 0.0) ? 1.0 / a / 255.0 : 0.0;
        for (int component = 0; component < 3; component++) {
            components[component] = resultingPixel[component] * unpremultiply;
        }
        components[3] = a;
    }
    

提交回复
热议问题