I am using quartz 2d to draw a pie chart.
I use layer to draw a reflection of the pie chart on the bottom.
I would like to add a transparent alpha gradient to the reflection to make the it more and more transparent until it gets invisible.
Someone has an idea ?
@EDIT : more details My pie chart is in a CGLayerRef.
I first draw this layer to the CGContextRef. Then I do a
CGContextTranslateCTM(context, 0, rect.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
To be upside down.
Then i draw my layer a new time
Thanks in advance,
Loic
You need to use an image mask. You can make the mask by drawing a gradient into a bitmap context:
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
CGContextRef gc = CGBitmapContextCreate(NULL, rect.size.width, rect.size.height, 8, rect.size.width, colorSpace, kCGImageAlphaNone);
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)[NSArray arrayWithObjects:(__bridge id)[UIColor whiteColor].CGColor, (__bridge id)[UIColor blackColor].CGColor, nil], NULL);
CGColorSpaceRelease(colorSpace);
CGContextDrawLinearGradient(gc, gradient, CGPointMake(0, 0), CGPointMake(0, rect.size.height), 0);
CGGradientRelease(gradient);
CGImageRef mask = CGBitmapContextCreateImage(gc);
CGContextRelease(gc);
(Remove __bridge
if you're not using ARC.)
Then you can use the mask before drawing the image:
CGContextTranslateCTM(context, 0, rect.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextClipToMask(context, rect, mask);
Don't forget to release the mask after you're done.
来源:https://stackoverflow.com/questions/8236375/how-to-add-a-transparent-gradient-mask-to-a-context