设置预览图层的框架会导致框架设置不正确

时间:2016-01-31 00:28:53

标签: ios swift pbjvision

我在PBJVision上遇到了一些麻烦。

我将它集成到Swift项目中,当我尝试设置预览图层的框架时,会导致框架不一致: img_1678

我有这段代码:

var _previewLayer: AVCaptureVideoPreviewLayer = PBJVision.sharedInstance().previewLayer
@IBOutlet weak var previewView: UIView! // this is the white view in the back

let bounds = self.previewView.layer.bounds
_previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
_previewLayer.bounds = bounds
_previewLayer.position = CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds))
previewView.layer.addSublayer(_previewLayer)

2 个答案:

答案 0 :(得分:2)

Have you tried resizing the frame of the _previewLayer when the previewView lays out its subviews?

Subclass UIView for your previewView, set a property for your AVCaptureVideoPreviewLayer, and set its frame to to match your view's bounds:

class PreviewView: UIView {

    let previewLayer: AVCaptureVideoPreviewLayer?

    override func layoutSubviews() {
        self.previewLayer?.frame = self.bounds;
    }
}

答案 1 :(得分:0)

我遇到了同样的问题。

我尝试了@rkyr推荐(在viewDidLayoutSubviews方法中设置框架),但没有成功。我还想在不添加子类的情况下修复它。

我能够通过2次更改修复它: - 确保将previewLayer定义为AVCaptureVideoPreviewLayerCALayer的子类)而不是CALayer,这是我的情况

var previewLayer: AVCaptureVideoPreviewLayer? // :CALayer
  • 确保已设置图层的框架,并在设置了图层会话的所有设置后将其添加到视图中:此代码有效:

    captureSession = AVCaptureSession()
    let captureDevice = AVCaptureDevice.default(for: AVMediaType.video)
    do {
        let input = try AVCaptureDeviceInput(device: captureDevice!)
        captureSession?.addInput(input)
    } catch {
        onErrorCloseAndReturn(error: error)
    }
    let dataOutput = AVCaptureVideoDataOutput()
    dataOutput.videoSettings = [((kCVPixelBufferPixelFormatTypeKey as NSString) as String): NSNumber(value: kCVPixelFormatType_32BGRA)]
    dataOutput.alwaysDiscardsLateVideoFrames = true
    if captureSession!.canAddOutput(dataOutput) {
        captureSession?.addOutput(dataOutput)
    }
    captureSession?.commitConfiguration()
    let queue = DispatchQueue(label: "captureQueue")
    dataOutput.setSampleBufferDelegate(self, queue: queue)
    captureSession?.startRunning()
    
    previewLayer = AVCaptureVideoPreviewLayer(session: captureSession!)
    previewLayer?.frame = self.view.layer.bounds
    self.view.layer.addSublayer(previewLayer!)
    

我帮忙...... e