我正在尝试快速掩盖图像。这是我的代码:
(通常,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时,它运行良好。但是,当我尝试获取生成的pngData()UIImage时,图像数据与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 contextimage renderer中并获得结果图像。

09-16 11:07