我正在尝试从另一个视图中绘制的给定 UIBezierPath 中裁剪 UIImage 。
这是我的代码:
// "self.imageEdited" is my initial image that needs to be cropped
let path = .... //my UIBezierPath
let layer = CAShapeLayer()
layer.path = path.cgPath
self.imageToEditView.layer.mask = layer
UIGraphicsBeginImageContextWithOptions(self.imageEdited.size, false, 1.0) // <-- Why it's not working with 0.0 ?
self.imageToEditView.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
//here "image" will be cropped but it haves white background
let croppedCGImage = image?.cgImage?.cropping(to: path.cgPath.boundingBox)
let croppedImage = UIImage(cgImage: croppedCGImage!)
self.imageToEditView.layer.mask = nil
UIImageWriteToSavedPhotosAlbum(croppedImage, nil, nil, nil)
此代码有效,可根据需要裁剪我的图像。 但是,如果我将 UIGraphicsBeginImageContextWithOptions 的比例因子更改为0.0(要获得设备的默认比例,这将创建相同的“图像 “但是当它运行时:
let croppedCGImage = image?.cgImage?.cropping(to: path.cgPath.boundingBox)
我无法裁剪正确的图像。它把它作为一个不同的部分。我应该扩大自己的道路吗?