UIColors can result in colors defined in different color spaces. White color will be monochrome.
This code demonstrates how to deal with it.
CGColorSpaceRef fillColorSpace = CGColorGetColorSpace([self.fillColor CGColor]); const float* fillColors = CGColorGetComponents([self.fillColor CGColor]); if (CGColorSpaceGetModel(fillColorSpace) == kCGColorSpaceModelRGB) { CGContextSetRGBFillColor(contextRef, fillColors[0],fillColors[1], fillColors[2], fillColors[3]); } else if (CGColorSpaceGetModel(fillColorSpace) == kCGColorSpaceModelMonochrome){ CGContextSetGrayFillColor(contextRef, fillColors[0], fillColors[1]); }
You can use this approach to convert monochrome colors to RGB colors:
if (CGColorSpaceGetModel(fillColorSpace) == kCGColorSpaceModelMonochrome){ const float* colors = CGColorGetComponents([self.fillColor CGColor]); self.fillColor = [UIColor colorWithRed:colors[0] green:colors[0] blue:colors[0] alpha:colors[1]]; }
Now the color is RGB, so you do not need to distinguish between CG functions for different color models.
const float* fillColors = CGColorGetComponents([self.fillColor CGColor]); CGContextSetRGBFillColor(contextRef, fillColors[0],fillColors[1], fillColors[2], fillColors[3]);
source share