更新时间:2023-09-29 14:40:16
用蒙版剪切上下文后,您实际上应该在该上下文上绘制一些东西。
After you clip context with mask you should actually draw something on that context.
此外:
UIGraphicsBeginImageContextWithOptions
支持缩放 UIGraphicsBeginImageContext
,另一个使用 CGBitmapContextCreate
。一个就足够了:),蒙版的源样本确定剪切区域的哪些点已更改
。换句话说,透明将变得透明UIGraphicsBeginImageContextWithOptions
to support scale factor.UIGraphicsBeginImageContext
and the other with CGBitmapContextCreate
. One is enough :)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);