使用蒙版剪切上下文后,您实际上应该在该上下文上绘制一些内容。
除此之外:
- 你应该使用
UIGraphicsBeginImageContextWithOptions
支持比例因子。
- 您正在创建两个上下文,其中之一是
UIGraphicsBeginImageContext
另一个与CGBitmapContextCreate
。一个就够了:)
- 你应该“翻转”你的面具的阿尔法,因为根据文档
The source samples of mask determine which points of the clipping area are changed
。换句话说透明就会变成透明
简单的示例代码,我将图像剪切到 imageView 中,然后将其设置回来:
UIGraphicsBeginImageContextWithOptions(self.imageView.frame.size, NO, 0.0);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, 0.0, self.imageView.frame.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGImageRef maskImage = [[UIImage imageNamed:@"mask.png"] CGImage];
CGContextClipToMask(context, self.imageView.bounds, maskImage);
CGContextTranslateCTM(context, 0.0, self.imageView.frame.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
[[self.imageView image] drawInRect:self.imageView.bounds];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
self.imageView.image = image;
使用示例CGImageCreateWithMask
:
UIImage *image = [UIImage imageNamed:@"image"];
CGImageRef originalMask = [UIImage imageNamed:@"mask"].CGImage;
CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(originalMask),
CGImageGetHeight(originalMask),
CGImageGetBitsPerComponent(originalMask),
CGImageGetBitsPerPixel(originalMask),
CGImageGetBytesPerRow(originalMask),
CGImageGetDataProvider(originalMask), nil, YES);
CGImageRef maskedImageRef = CGImageCreateWithMask(image.CGImage, mask);
UIImage *maskedImage = [UIImage imageWithCGImage:maskedImageRef scale:image.scale orientation:image.imageOrientation];
CGImageRelease(mask);
CGImageRelease(maskedImageRef);