How to Add Live Camera Preview to UIView

前端 未结 5 489
温柔的废话
温柔的废话 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:34

    Swift 3:

    @IBOutlet weak var cameraContainerView:UIView!
    
    var imagePickers:UIImagePickerController?
    

    On ViewDidLoad:

    override func viewDidLoad() {
    
            super.viewDidLoad()
            addImagePickerToContainerView()
    
        }
    

    Add Camera Preview to the container view:

    func addImagePickerToContainerView(){
    
            imagePickers = UIImagePickerController()
            if UIImagePickerController.isCameraDeviceAvailable( UIImagePickerControllerCameraDevice.front) {
                imagePickers?.delegate = self
                imagePickers?.sourceType = UIImagePickerControllerSourceType.camera
    
                //add as a childviewcontroller
                addChildViewController(imagePickers!)
    
                // Add the child's View as a subview
                self.cameraContainerView.addSubview((imagePickers?.view)!)
                imagePickers?.view.frame = cameraContainerView.bounds
                imagePickers?.allowsEditing = false
                imagePickers?.showsCameraControls = false
                imagePickers?.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    
            }
        }
    

    On custom button action:

    @IBAction func cameraButtonPressed(_ sender: Any) {
    
             if UIImagePickerController.isSourceTypeAvailable(.camera){
                imagePickers?.takePicture()
    
             } else{
    
              //Camera not available.
            }  
        }
    

提交回复
热议问题