swiftUI中insertSublayer的替代方法是什么

时间:2019-10-20 13:26:59

标签: swift xcode avfoundation swiftui

我正在创建一个cameraApp,这是我正在做的项目的一部分,并且对swiftUI来说还比较陌生。我正在使用AVFoundation,并且需要创建一个PreviewLayer。但是,我无法创建previewLayer,因为我不知道如何显示它。我遵循了一些教程并阅读了Apple的文档。

这是我的代码的样子

struct ContentView: View {

    var captureSession = AVCaptureSession()
    var currentCamera: AVCaptureDevice?
    var photoOutput: AVCapturePhotoOutput?
    var cameraPreviewLayer: AVCaptureVideoPreviewLayer?


    func setupCaptureSession() {
        captureSession.canSetSessionPreset(.high)
    }

    mutating func setupDevice() {
        let videoDevice = AVCaptureDevice.default(.builtInWideAngleCamera,
        for: .video, position: .unspecified)

        currentCamera = videoDevice
    }

    func setupInputOutput() {
        do {
            let captureDeviceInput = try AVCaptureDeviceInput(device: currentCamera!)
            captureSession.addInput(captureDeviceInput)
            photoOutput!.supportedPhotoCodecTypes(for: .jpg)
        } catch {
            print("err")
        }
    }

    mutating func setupPreviewLayer() {
        cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        cameraPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
        cameraPreviewLayer?.connection?.videoOrientation = 
        AVCaptureVideoOrientation.landscapeRight
        cameraPreviewLayer?.frame = self.view.frame
        self.view.insertSublayer(cameraPreviewLayer!, at: 0)
    }

    func startRunningCaptureSession() {
        captureSession.startRunning()
    }    


    var body: some View {
        Text("Hello World")
            .frame(maxWidth: .infinity, maxHeight: .infinity)

    }
}

0 个答案:

没有答案