When drawing white, a transparent color is obtained

So, in my user view, I'm trying to draw a white / gray gradient using Core Graphics. I have the following code:

UIColor *color1 = [UIColor whiteColor]; UIColor *color2 = [UIColor colorWithRed:209.0/255.0 green:212.0/255.0 blue:217.0/255.0 alpha:1.0]; CFMutableArrayRef colors = CFArrayCreateMutable(NULL, 0, NULL); CFArrayAppendValue(colors, color1.CGColor); CFArrayAppendValue(colors, color2.CGColor); CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB(); CGFloat locations[2] = {0.0, 1.0}; CGGradientRef gradient = CGGradientCreateWithColors(colorspace, colors, locations); CGContextDrawLinearGradient(UIGraphicsGetCurrentContext(), gradient, topCenter, bottomCenter, kCGGradientDrawsAfterEndLocation); 

I think this code is pretty simple and should lead to a nice white / gray gradient. But this is not so; he draws a transparent / gray gradient.

I think this may have something to do with the background color of the view, which is [UIColor clearColor] . But I cannot change this, since I need some parts of my view to be transparent.

Any ideas?

+4
source share
2 answers
 UIColor *color1 = [UIColor whiteColor]; 

The above line is likely to create a color in the color space of shades of gray.

Try this instead:

 UIColor *color1 = [UIColor colorWithRed:1.f green:1.f blue:1.f alpha:1.f]; 
+4
source

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]); 
+4
source

All Articles