我正在尝试裁剪具有特定关注区域的相机拍摄的图像。为了找到比例作物矩形,我使用previewLayer.metadataOutputRectConverted
方法。但是裁剪后我得到了错误的比率。
调试示例:
(lldb) po rectOfInterest.width / rectOfInterest.height
0.7941176470588235
(lldb) po image.size.width / image.size.height
0.75
(lldb) po outputRect.width / outputRect.height
0.9444444444444444
(lldb) po Double(cropped.width) / Double(cropped.height)
0.7080152671755725
如您所见,我希望裁剪的图像比例将是~0.79
,与我用于裁剪的rectOfInterest
一样。
方法:
private func makeImageCroppedToRectOfInterest(from image: UIImage) -> UIImage {
let previewLayer = cameracontroller.previewLayer
let rectOfInterest = layoutLayer.layoutRect
let outputRect = previewLayer.metadataOutputRectConverted(fromLayerRect: rectOfInterest)
guard let cgImage = image.cgImage else {
return image
}
let width = CGFloat(cgImage.width)
let height = CGFloat(cgImage.height)
let cropRect = CGRect(x: outputRect.origin.x * width,y: outputRect.origin.y * height,width: outputRect.size.width * width,height: outputRect.size.height * height)
guard let cropped = cgImage.cropping(to: cropRect) else {
return image
}
return UIImage(cgImage: cropped,scale: image.scale,orientation: image.imageOrientation)
}