AVCaptureVideoPreviewLayer似乎在逃避父边界

时间:2019-01-29 04:00:08

标签: ios view storyboard constraints addsubview

我在将AVCaptureVideoPreviewLayer放入其父范围内时遇到问题。

这是上下文代码:

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

我有

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

发生以下情况:

enter image description here

当我有

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

发生这种情况 enter image description here

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

enter image description here

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

enter image description here

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

目标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]];

快速

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])