禁用相机视图增长动画

Disable camera view growing animation

目前,我有一个 vie 控制器,它以模态方式呈现一个包含相机的视图控制器。但是,每当我转换时,预览层都有一个动画,因此它从左上角循环增长以填充屏幕的其余部分。我试过禁用 CALayer 隐式动画但没有成功。这是出现视图时的代码。

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    previewLayer?.frame = self.view.frame
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    capturedImageView.center = self.view.center
    captureSession = AVCaptureSession()
    if usingFrontCamera == true {
    captureSession?.sessionPreset = AVCaptureSession.Preset.hd1920x1080
    }
    else {
    captureSession?.sessionPreset = AVCaptureSession.Preset.hd1280x720
    }

    captureDevice = AVCaptureDevice.default(for: AVMediaType.video)


    do {
        let input = try AVCaptureDeviceInput(device: captureDevice!)

        if (captureSession?.canAddInput(input) != nil) {
            captureSession?.addInput(input)

            stillImageOutput = AVCapturePhotoOutput()

            captureSession?.addOutput(stillImageOutput!)
            previewLayer = AVCaptureVideoPreviewLayer(session: captureSession!)
            previewLayer?.videoGravity = AVLayerVideoGravity.resizeAspect
            self.view.layer.addSublayer(previewLayer!)
            captureSession?.startRunning()


        }


    } catch {

    }
}

有什么方法可以去掉这个成长动画吗?这是问题的 gif:

你分两个阶段做事。在 viewWillAppear 中,您添加预览图层时根本没有给它任何大小,因此它是零原点处的零大小图层:

previewLayer = AVCaptureVideoPreviewLayer(session: captureSession!)
previewLayer?.videoGravity = AVLayerVideoGravity.resizeAspect
self.view.layer.addSublayer(previewLayer!)

然后,在 viewDidAppear 中,您通过给它一个实际的帧来增加预览层:

previewLayer?.frame = self.view.frame

这两个阶段依次发生,我们可以看到预览图层的帧变化引起的跳跃。

如果你不想看到跳跃,就不要那样做。不要添加预览层,直到你可以先给它 实际 帧。

当你改变图层框架时,有一个隐式动画。您可以使用 CATransaction 来禁用动画。

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    CATransaction.begin()
    CATransaction.setDisableActions(true)
    previewLayer?.frame = self.view.frame
    CATransaction.commit()
}