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

后端 未结 4 1374
梦谈多话
梦谈多话 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:30

    In Swift 4:

    I prefer to never force-unwrap to avoid crashes, so I use optionals and guards in mine.

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

提交回复
热议问题