OGeek|极客世界-中国程序员成长平台

标题: ios - 在自定义相机swift + xcode中切换相机时平滑过渡 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:19
标题: ios - 在自定义相机swift + xcode中切换相机时平滑过渡

我正在使用 swift 3 和 xcode 创建我的自定义相机 View 。

我已经让它工作了,但我面临一个小问题。要从前/后切换摄像头设备,我停止 session ,从 View 中删除视频预览层,然后创建一个新 session 并从前置摄像头添加一个新的视频预览层。这使得新相机突然出现。我想要相机设备之间的平滑过渡。我该怎么做?

这是我加载相机的代码:

func loadCamera()
{

    session?.stopRunning()
    videoPreviewLayer?.removeFromSuperlayer()

    session = AVCaptureSession()
    session!.sessionPreset = AVCaptureSessionPresetPhoto


    var backCamera = AVCaptureDevice.defaultDevice(withDeviceType: .builtInWideAngleCamera, mediaType: AVMediaTypeVideo, position: .front)

    if cameraPos == "back"
    {
        backCamera = AVCaptureDevice.defaultDevice(withDeviceType: .builtInWideAngleCamera, mediaType: AVMediaTypeVideo, position: .back)
    }

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

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

        stillImageOutput = AVCapturePhotoOutput()


        if session!.canAddOutput(stillImageOutput) {
            session!.addOutput(stillImageOutput)


            videoPreviewLayer = AVCaptureVideoPreviewLayer(session: session)

            videoPreviewLayer?.frame = cameraView.bounds
            videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
            videoPreviewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait


            cameraView.layer.addSublayer(videoPreviewLayer!)
            session!.startRunning()

        }   
    }
}

我从 viewWillAppear 中调用它

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    loadCamera()
}

当用户点击更改相机时,我会调用加载相机

@IBAction func changeCamera(_ sender: UIButton) {

    if cameraPos == "back"
    {cameraPos = "front"}

    else
    {cameraPos = "back"}


    loadCamera()
}



Best Answer-推荐答案


在 loadCamera() 中,您需要从前端捕获设备创建一个 AVCaptureInput。在某些相机单例上同时保留后输入和前输入是一种很好的做法。可以通过移除所有输入然后分配另一个输入来实现前后之间的平滑过渡。

func show(back: Bool) {
  session.beginConfiguration()
  if let inputs = session.inputs as? [AVCaptureDeviceInput] {
    for input in inputs {
      session.removeInput(input)
    }
  }
  if back {
    if session.canAddInput(backInput) {
      session.addInput(backInput)
    }
  } else {
    if session.canAddInput(frontInput) {
      session.addInput(frontInput)
    }
  }
  session.commitConfiguration()
}

关于ios - 在自定义相机swift + xcode中切换相机时平滑过渡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41121401/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (https://ogeek.cn/) Powered by Discuz! X3.4