How to add a transparent gradient mask to a context

后端 未结 1 1711
时光取名叫无心
时光取名叫无心 2021-02-06 17:59

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 th

相关标签:
1条回答
  • 2021-02-06 18:16

    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.

    0 讨论(0)
提交回复
热议问题