How to get color components of a CGColor correctly

后端 未结 6 1153
日久生厌
日久生厌 2021-01-02 14:04

I have a UILabel with black color;

i am writing the following code to get black color\'s components.

UIColor *aColor = [aLabel.textColor retain];
con         


        
6条回答
  •  一生所求
    2021-01-02 14:15

    Most likely wrong colorspace. I guess the alpha component of the grayscale colorspace gets where you think the green component should be.
    I use this function to create a string from UIColor, I only encounter RGB and Grayscale colorspaces, so I just interpret every color with less than 4 (R+G+B+A) components as grayscale.

    if (CGColorGetNumberOfComponents(color.CGColor) < 4) {
        const CGFloat *components = CGColorGetComponents(color.CGColor);
        color = [UIColor colorWithRed:components[0] green:components[0] blue:components[0] alpha:components[1]];
    }
    if (CGColorSpaceGetModel(CGColorGetColorSpace(color.CGColor)) != kCGColorSpaceModelRGB) {
        NSLog(@"no rgb colorspace");
        // do seomthing
    }
    const CGFloat *components = CGColorGetComponents(color.CGColor);
    NSString *colorAsString = [NSString stringWithFormat:@"%f,%f,%f,%f", components[0], components[1], components[2], components[3]];
    

    of course this method is not save for all cases, you should adopt it to your requirements.

提交回复
热议问题