How to Add Live Camera Preview to UIView

前端 未结 5 480
温柔的废话
温柔的废话 2020-12-04 16:45

I run into a problem, I\'m trying to solve within UIView boundary, is there any way to Add Camera Preview to UIView? And Add other content on top of The UIView (Buttons, Lab

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 17:38

    swift 5 easy way

    import UIKit
    import AVFoundation
    
    class ViewController: UIViewController, UINavigationControllerDelegate,UIImagePickerControllerDelegate{
    
    //Camera Capture requiered properties
    var imagePickers:UIImagePickerController?
    
    @IBOutlet weak var customCameraView: UIView!
    
    override func viewDidLoad() {
        addCameraInView()
        super.viewDidLoad()
    }
    
    func addCameraInView(){
    
        imagePickers = UIImagePickerController()
        if UIImagePickerController.isCameraDeviceAvailable( UIImagePickerController.CameraDevice.rear) {
            imagePickers?.delegate = self
            imagePickers?.sourceType = UIImagePickerController.SourceType.camera
    
            //add as a childviewcontroller
            addChild(imagePickers!)
    
            // Add the child's View as a subview
            self.customCameraView.addSubview((imagePickers?.view)!)
            imagePickers?.view.frame = customCameraView.bounds
            imagePickers?.allowsEditing = false
            imagePickers?.showsCameraControls = false
            imagePickers?.view.autoresizingMask = [.flexibleWidth,  .flexibleHeight]
            }
        }
    
        @IBAction func cameraButtonPressed(_ sender: Any) {
    
             if UIImagePickerController.isSourceTypeAvailable(.camera){
                imagePickers?.takePicture()
    
             } else{
    
              //Camera not available.
            }
        }
    }
    

提交回复
热议问题