How to crop an image from AVCapture to a rect seen on the display

后端 未结 4 1302
梦谈多话
梦谈多话 2021-01-30 08:59

This is driving me crazy because I can\'t get it to work. I have the following scenario:

I\'m using an AVCaptureSession and an AVCaptureVideoPreviewLa

4条回答
  •  长发绾君心
    2021-01-30 09:19

    In Swift 3:

    private func cropToPreviewLayer(originalImage: UIImage) -> UIImage {
        let outputRect = previewLayer.metadataOutputRectConverted(fromLayerRect: previewLayer.bounds)
        var cgImage = originalImage.cgImage!
        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)
        
        cgImage = cgImage.cropping(to: cropRect)!
        let croppedUIImage = UIImage(cgImage: cgImage, scale: 1.0, orientation: originalImage.imageOrientation)
        
        return croppedUIImage
    }
    

提交回复
热议问题