How to expand camera view to full screen in swift - UIImagePickerController

10,488

Solution 1

import UIKit
import AVFoundation

class CameraViewController: UIViewController {

    // MARK: @IBOutlet

    @IBOutlet weak var overlayCamera: UIView! 
    @IBOutlet weak var capturedImage: UIImageView! 

    // MARK: Local Variables

    var captureSession: AVCaptureSession?
    var stillImageOutput: AVCaptureStillImageOutput?
    var previewLayer: AVCaptureVideoPreviewLayer?

    // MARK: Overrides

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        previewLayer!.frame = overlayCamera.bounds
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        let tapGesture = UITapGestureRecognizer(target: self, action: "cameraDidTap")
        overlayCamera.addGestureRecognizer(tapGesture)
    }

    override func viewWillAppear(animated: Bool) {
        self.navigationController?.setNavigationBarHidden(true, animated: false)
        super.viewWillAppear(animated)

        captureSession = AVCaptureSession()
        captureSession!.sessionPreset = AVCaptureSessionPresetPhoto

        let backCamera = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)

        var error: NSError?
        var input: AVCaptureDeviceInput!
        do {
            input = try AVCaptureDeviceInput(device: backCamera)
        } catch let error1 as NSError {
            error = error1
            input = nil
        }

        if error == nil && captureSession!.canAddInput(input) {
            captureSession!.addInput(input)

            stillImageOutput = AVCaptureStillImageOutput()
            stillImageOutput!.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
            if captureSession!.canAddOutput(stillImageOutput) {
                captureSession!.addOutput(stillImageOutput)

                previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
                previewLayer!.videoGravity = AVLayerVideoGravityResizeAspectFill
                previewLayer!.connection?.videoOrientation = AVCaptureVideoOrientation.Portrait
                overlayCamera.layer.addSublayer(previewLayer!)

                captureSession!.startRunning()
            }
        }
    }

    override func viewWillDisappear(animated: Bool) {
        self.navigationController?.setNavigationBarHidden(false, animated: false)
        super.viewWillDisappear(animated)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    // function for UITapGestureRecognizer for camera tap
    func cameraDidTap() {

        if let videoConnection = stillImageOutput!.connectionWithMediaType(AVMediaTypeVideo) {
            videoConnection.videoOrientation = AVCaptureVideoOrientation.Portrait
            stillImageOutput?.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: {(sampleBuffer, error) in
                if (sampleBuffer != nil) {
                    let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
                    let dataProvider = CGDataProviderCreateWithCFData(imageData)
                    let cgImageRef = CGImageCreateWithJPEGDataProvider(dataProvider, nil, true, CGColorRenderingIntent.RenderingIntentDefault)

                    let image = UIImage(CGImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.Right)
                    self.capturedImage.image = image
                }
            })
        }
    }
}

Solution 2

It works for me:

Set AVCaptureSession():

let captureSession = AVCaptureSession()

guard let captureDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: AVMediaType.video, position: .back) else { return }
guard let input = try? AVCaptureDeviceInput(device: captureDevice) else { return }    
captureSession.addInput(input)
captureSession.startRunning()

Set AVCaptureVideoPreviewLayer():

let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.videoGravity = .resizeAspectFill
view.layer.addSublayer(previewLayer)
previewLayer.frame = view.frame

Solution 3

In previewLayer just set videoGravity to aspectFill:

let previewLayer = AVCaptureVideoPreviewLayer()

previewLayer.videoGravity = .resizeAspectFill
Share:
10,488
SteBra
Author by

SteBra

Updated on June 14, 2022

Comments

  • SteBra
    SteBra almost 2 years

    I am using UIImagePickerController to snap a photo with a pone and use that photo in the app later.

    This is my code for starting a camera:

    imagePicker = UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = .Camera
    imagePicker.showsCameraControls = false
    imagePicker.cameraOverlayView = customViewTakePhoto()
    
    presentViewController(imagePicker, animated: true, completion: nil)
    

    It all works fine, the camera starts, I am able to fetch photo once it's taken, but there is only one thing I cannot figure out, and that is:

    How to make camera view across the entire screen, before the photo is taken?

    Here are the images showing exactly what I need

    This is my View as it is right now (I highly recommend the book, btw):

    enter image description here

    and this is what I need (Fullscreen camera view):

    enter image description here