Cropping a captured image exactly to how it looks in AVCaptureVideoPreviewLayer

后端 未结 3 1047
梦毁少年i
梦毁少年i 2021-02-01 07:54

I have a photo app that is using AV Foundation. I have setup a preview layer using AVCaptureVideoPreviewLayer that takes up the top half of the screen. So when the user is tryin

3条回答
  •  闹比i
    闹比i (楼主)
    2021-02-01 08:35

    Here's @Erik Allen's answer in Swift 3:

    let originalSize: CGSize
    let visibleLayerFrame = self?.photoView.bounds
    
    // Calculate the fractional size that is shown in the preview
    let metaRect = (self?.videoPreviewLayer?.metadataOutputRectOfInterest(for: visibleLayerFrame ?? CGRect.zero)) ?? CGRect.zero
    
    if (image.imageOrientation == UIImageOrientation.left || image.imageOrientation == UIImageOrientation.right) {
        // For these images (which are portrait), swap the size of the
        // image, because here the output image is actually rotated
        // relative to what you see on screen.
        originalSize = CGSize(width: image.size.height, height: image.size.width)
    } else {
        originalSize = image.size
    }
    
    let cropRect: CGRect = CGRect(x: metaRect.origin.x * originalSize.width, y: metaRect.origin.y * originalSize.height, width: metaRect.size.width * originalSize.width, height: metaRect.size.height * originalSize.height).integral
    
    if let finalCgImage = image.cgImage?.cropping(to: cropRect) {
        let finalImage = UIImage(cgImage: finalCgImage, scale: 1.0, orientation: image.imageOrientation)
    
        // User your image...
    }
    

提交回复
热议问题