[英]CGImage Masking with UIImage pngData()
I'm trying to mask an image in swift. 我正在尝试快速掩盖图像。 Here's my code:
这是我的代码:
(Normally, originalImg
is an image that is loaded from UIImagePickerController
and then cropped by UIGraphicsGetImageFromCurrentImageContext()
, and (通常,
originalImg
是从UIImagePickerController
加载的图像,然后由UIGraphicsGetImageFromCurrentImageContext()
裁剪,并且
makedImage
is an image that is drawn by the user, created by 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)!)
}
When I display the resulted UIImage
to UIImageView
, it works well. 当我将生成的
UIImage
显示到UIImageView
,它运行良好。 However, when I try to get the pngData()
of the resulted UIImage
, the image data is identical to originalImg
. 但是,当我尝试获取结果
UIImage
的pngData()
时,图像数据与originalImg
相同。
I also tried to export the pngData()
of the resulted image from Xcode, but it is still the same as originalImg
. 我还尝试从Xcode导出结果图像的
pngData()
,但它仍然与originalImg
相同。
Image: https://imgur.com/tEVBWUQ (then click the 'Export...' button and save as png image) 图片: https : //imgur.com/tEVBWUQ (然后单击“导出...”按钮并另存为png图像)
How can I really mask an image? 我如何真正掩盖图像?
Just draw a masked image into 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;
}
Also you can draw image into bitmap context or image renderer and get result image. 您也可以将图像绘制到位图上下文或图像渲染器中并获取结果图像。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.