How to add a transparent gradient mask to a context

你。 提交于 2019-12-20 17:26:20

问题


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


回答1:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!