且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

CGContextClipToMask返回空白图像

更新时间:2023-09-29 14:40:16

用蒙版剪切上下文后,您实际上应该在该上下文上绘制一些东西。

After you clip context with mask you should actually draw something on that context.

此外:


  • 您应该使用 UIGraphicsBeginImageContextWithOptions 支持缩放

  • 您正在创建两个上下文,一个使用 UIGraphicsBeginImageContext ,另一个使用 CGBitmapContextCreate 。一个就足够了:)

  • 您应该翻转蒙版的Alpha,因为根据文档,蒙版的源样本确定剪切区域的哪些点已更改。换句话说,透明将变得透明

  • you should use UIGraphicsBeginImageContextWithOptions to support scale factor.
  • you're creating two context, one with UIGraphicsBeginImageContext and the other with CGBitmapContextCreate. One is enough :)
  • you should "flip" alpha of your mask, because according to docs The source samples of mask determine which points of the clipping area are changed. The other words transparent will become transparent

简单的示例代码,在其中我将图像剪辑在imageView中,然后将其重新设置:

Simple example code, where I clip image inside imageView and then set it back:

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);