How to add a transparent gradient mask to a context

会有一股神秘感。 提交于 2019-12-03 03:58:56

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.

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