AVCaptureVideoPreviewLayer 似乎正在逃避父边界

AVCaptureVideoPreviewLayer appears to be escaping parent bounds

我在将 AVCaptureVideoPreviewLayer 安装在其父边界内时遇到问题。

这里是上下文代码:

    capturePreview = AVCaptureVideoPreviewLayer(session: captureSession)
    guard let capturePreview = capturePreview else { return }

当我有

   capturePreview.frame = cameraView.bounds
   cameraView.layer.addSublayer(capturePreview)

发生以下情况:

当我有

capturePreview.bounds = cameraView.layer.bounds
cameraView.layer.addSublayer(capturePreview)

这会发生

我正在尝试让预览图层适合下一张图片中的黑框

根据我在文档中看到的内容,我不确定哪里出错了。谢谢你的帮助。作为参考,我将添加我在情节提要中给出的约束。

您是否尝试过使用类似的东西:

capturePreview.frame = cameraView.bounds
cameraView.layer.addSublayer(capturePreview)
cameraView.clipsToBounds = true

您是否添加了将 capturePreview 附加到 cameraView 的约束?您将需要在代码中执行此操作。添加约束,使 capturePreview 的左、右、上、下边缘附加到 cameraView 的相应边缘。

Objective C

NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:capturePreview attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:cameraView attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0];
NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:capturePreview attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:cameraView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0.0];
NSLayoutConstraint *rightConstraint = [NSLayoutConstraint constraintWithItem:capturePreview attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:cameraView attribute:NSLayoutAttributeRight multiplier:1.0 constant:0.0];
NSLayoutConstraint *bottomConstraint = [NSLayoutConstraint constraintWithItem:capturePreview attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:cameraView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0];

[NSLayoutConstraint activateConstraints:@[topConstraint, bottomConstraint, leftConstraint, rightConstraint]];

Swift

let topConstraint = NSLayoutConstraint(item: capturePreview, attribute: .top, relatedBy: .equal, toItem: cameraView, attribute: .top, multiplier: 1.0, constant: 0.0)
let bottomConstraint = NSLayoutConstraint(item: capturePreview, attribute: .bottom, relatedBy: .equal, toItem: cameraView, attribute: .bottom, multiplier: 1.0, constant: 0.0)
let leftConstraint = NSLayoutConstraint(item: capturePreview, attribute: .left, relatedBy: .equal, toItem: cameraView, attribute: .left, multiplier: 1.0, constant: 0.0)
let rightConstraint = NSLayoutConstraint(item: capturePreview, attribute: .right, relatedBy: .equal, toItem: cameraView, attribute: .right, multiplier: 1.0, constant: 0.0)
NSLayoutConstraint.activate([topConstraint, bottomConstraint, leftConstraint, rightConstraint])