我正在尝试快速屏蔽图像。这是我的代码:
(通常,originalImg
是从 UIImagePickerController
加载的图像,然后由 UIGraphicsGetImageFromCurrentImageContext()
裁剪,并且
makedImage
是用户绘制的图像,由 UIGraphicsGetImageFromCurrentImageContext()
) 创建
func imageMasking(_ originalImg: UIImage, maskImage: UIImage) -> UIImage {
let cgMaskImage = maskImage.cgImage!
let mask = CGImage(maskWidth: cgMaskImage.width, height: cgMaskImage.height, bitsPerComponent: cgMaskImage.bitsPerComponent, bitsPerPixel: cgMaskImage.bitsPerPixel, bytesPerRow: cgMaskImage.bytesPerRow, provider: cgMaskImage.dataProvider!, decode: nil, shouldInterpolate: true)!
return UIImage(cgImage: originalImg.cgImage!.masking(mask)!)
}
当我将结果 UIImage
显示到 UIImageView
时,效果很好。但是,当我尝试获取结果 UIImage
的 pngData()
时,图像数据与 originalImg
相同。
我还尝试从 Xcode 导出结果图像的 pngData()
,但它仍然与 originalImg
相同。
图片:https://imgur.com/tEVBWUQ (然后单击“导出...”按钮并另存为 png 图像)
我怎样才能真正屏蔽图像?
最佳答案
只需在 image context 中绘制蒙版图像即可:
func drawImage(_ image: UIImage) -> UIImage?
{
guard let coreImage = image.cgImage else {
return nil;
}
UIGraphicsBeginImageContext(CGSize(width: coreImage.width, height: coreImage.height))
image.draw(in: CGRect(x: 0.0, y: 0.0, width: coreImage.width, height: coreImage.height))
let resultImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return resultImage;
}
您也可以将图像绘制到bitmap context 中或 image renderer并得到结果图像。
关于ios - 使用 UIImage pngData() 进行 CGImage 掩蔽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53967126/