Search code examples
pdfquartz-graphicsradial-gradients

CGContextDrawRadialGradient not rendering alpha in PDF?


I have the following drawing, which renders a circle with full color at the center fading to 0 alpha at the edges. When drawing this to the screen, it looks perfect. However, when I draw the same thing in a PDF context (CGPDFContextCreate), the whole circle comes out opaque. If I draw any other regular path in the PDF, then alpha renders fines. So just the gradient doesn't work. Is this a bug or am I missing something?

        CGColorSpaceRef myColorspace = CGColorSpaceCreateDeviceRGB();
        size_t num_locations = 2;
        CGFloat locations[2] = { 1.0, 0.0 };

        CGColorRef color = [[UIColor redColor]CGColor];  
        CGFloat *k = (CGFloat *)CGColorGetComponents(color);
        CGFloat components[8] = { k[0], k[1], k[2], 0.0,    k[0], k[1], k[2], 1.0 };

        CGGradientRef myGradient = CGGradientCreateWithColorComponents(myColorspace, components, locations, num_locations);

        CGPoint c = CGPointMake(160, 160);
        CGContextDrawRadialGradient(pdfContext, myGradient, c, 0, c, 60, 0);

Solution

  • Official response from Apple tech support:

    Quartz ignores the alpha value of colors in gradients (or shadings) when capturing a gradient (or shading) to a PDF document and instead treats all colors as if they are completely opaque. In addition, Quartz ignores the global alpha in the context when it records gradients (or shadings) into a PDF document. One possible work-around is to capture a shading as bits using a bitmap context and use the resulting bits to create a CGImage that you draw through the clipping area. This produces pre-rendered gradients (or shadings) but does capture the alpha content into a PDF document. You should not perform this pre-rendering for gradients (or shadings) that don't contain alpha.