我正在尝试裁剪具有特定兴趣的相机会话捕获的图像。为了找到比例作物rect我正在使用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)
}
我不是专家,但我认为您误解了该metadataOutputRectConverted
方法的用法。您的代码无法以相同的长宽比返回裁剪后的图像,因为您实际上是在互不相乘(实际上是无关的数字)。
你可以试试这个方法
previewLayer.layerRectConverted(fromMetadataOutputRect: CGRect(x: 0, y: 0, width: 1, height: 1))
弄清楚从中进行的实际计算metadataOututRectConverted
是什么。
我想您可以更好地解释您想要实现的目标,或者提供一个示例项目(或者至少提供一些有关您正在使用的实际图像/矩形的上下文),以帮助我们进行调试(如果您想要更多)对此有所帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句