How to Add Live Camera Preview to UIView

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

    iOS 13/14 and Swift 5.3:

    private var imageVC: UIImagePickerController?
    

    and then call showCameraVC() when you want to show the camera view

    func showCameraVC() {    
        self.imageVC = UIImagePickerController()
    
        if UIImagePickerController.isCameraDeviceAvailable(.front) {
            self.imageVC?.sourceType = .camera
            self.imageVC?.cameraDevice = .front
            self.imageVC?.showsCameraControls = false
                    
            let screenSize = UIScreen.main.bounds.size
            let cameraAspectRatio = CGFloat(4.0 / 3.0)
            let cameraImageHeight = screenSize.width * cameraAspectRatio
            let scale = screenSize.height / cameraImageHeight
            self.imageVC?.cameraViewTransform = CGAffineTransform(translationX: 0, y: (screenSize.height - cameraImageHeight)/2)
            self.imageVC?.cameraViewTransform = self.imageVC!.cameraViewTransform.scaledBy(x: scale, y: scale)
        
            self.imageVC?.view.frame = CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height)
            self.view.addSubview(self.imageVC!.view)
            self.view.sendSubviewToBack(self.imageVC!.view)
        }
    }
    

    Camera view will be also fullscreen (other answers wouldn't fix a letterboxed view)

提交回复
热议问题