【发布时间】:2020-03-01 04:32:16
【问题描述】:
我正在尝试裁剪具有特定兴趣区域的相机会话捕获的图像。为了找到比例裁剪矩形,我使用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)
}
【问题讨论】:
标签: ios swift image camera crop