当前位置 : 主页 > 手机开发 > 其它 >

在Swift中使用按钮切换相机

来源:互联网 收集:自由互联 发布时间:2021-06-11
这似乎可以将相机从后面切换到前面,但我正在尝试提出一个’if’语句,以便我也可以将其切换回来.任何想法或建议? @IBAction func didTouchSwitchButton(sender: UIButton) { let camera = getDevice(.Fron
这似乎可以将相机从后面切换到前面,但我正在尝试提出一个’if’语句,以便我也可以将其切换回来.任何想法或建议?

@IBAction func didTouchSwitchButton(sender: UIButton) {


    let camera = getDevice(.Front)
    let cameraBack = getDevice(.Back)


    do {
        input = try AVCaptureDeviceInput(device: camera)
    } catch let error as NSError {
        print(error)
        input = nil
    }
    if(captureSession?.canAddInput(input) == true){
        captureSession?.addInput(input)
        stillImageOutput?.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG]
        if(captureSession?.canAddOutput(stillImageOutput) == true){
            captureSession?.addOutput(stillImageOutput)
            previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
            previewLayer?.frame = cameraView.bounds
            cameraView.layer.addSublayer(previewLayer!)
            captureSession?.startRunning()
        }
    }

}

func switchCamera(_ sender: UIButton) {
    if let session = AVCaptureSession() {
        let currentCameraInput: AVCaptureInput = session.inputs[0]
        session.removeInput(currentCameraInput)
        var newCamera: AVCaptureDevice
        newCamera = AVCaptureDevice.default(for: AVMediaType.video)!

            if (currentCameraInput as! AVCaptureDeviceInput).device.position == .back {
                UIView.transition(with: self.cameraView, duration: 0.5, options: .transitionFlipFromLeft, animations: {
                    newCamera = self.cameraWithPosition(.front)!
                }, completion: nil)
            } else {
                UIView.transition(with: self.cameraView, duration: 0.5, options: .transitionFlipFromRight, animations: {
                    newCamera = self.cameraWithPosition(.back)!
                }, completion: nil)
            }
            do {
                try self.captureSession?.addInput(AVCaptureDeviceInput(device: newCamera))
            }
            catch {
                print("error: \(error.localizedDescription)")
            }

    }
}

func cameraWithPosition(_ position: AVCaptureDevice.Position) -> AVCaptureDevice? {
    let deviceDescoverySession = AVCaptureDevice.DiscoverySession.init(deviceTypes: [AVCaptureDevice.DeviceType.builtInWideAngleCamera], mediaType: AVMediaType.video, position: AVCaptureDevice.Position.unspecified)

    for device in deviceDescoverySession.devices {
        if device.position == position {
            return device
        }
    }
    return nil
}
网友评论