So, I'm trying to use the camera on my phone in my app, and I was successful, but unfortunately, when using the preview, the layer does not fill the entire screen Here is an image to show you what it looks like
Here's my code:
if let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) {
self.previewLayer = previewLayer
self.view.layer.addSublayer(self.previewLayer)
self.previewLayer.frame = self.view.layer.frame
captureSession.startRunning()
let dataOutput = AVCaptureVideoDataOutput()
dataOutput.videoSettings = [(kCVPixelBufferPixelFormatTypeKey as NSString):NSNumber(value:kCVPixelFormatType_32BGRA)]
dataOutput.alwaysDiscardsLateVideoFrames = true
if captureSession.canAddOutput(dataOutput) {
captureSession.addOutput(dataOutput)
}
captureSession.commitConfiguration()
let queue = DispatchQueue(label: "com.Osmo.captureQueue")
dataOutput.setSampleBufferDelegate(self, queue: queue)
}
This may happen because you're trying to set a preview layer's frame from view which has auto layout constraints. Try to add an override of viewDidLayoutSubviews
method to your view controller:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.previewLayer.frame = self.view.layer.bounds
}
Please try the following:
if let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) {
self.previewLayer = previewLayer
self.previewLayer.frame = self.view.bounds
self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
self.view.layer.insertSublayer(self.previewLayer, at: 0)
captureSession.startRunning()
let dataOutput = AVCaptureVideoDataOutput()
dataOutput.videoSettings = [(kCVPixelBufferPixelFormatTypeKey as NSString):NSNumber(value:kCVPixelFormatType_32BGRA)]
dataOutput.alwaysDiscardsLateVideoFrames = true
if captureSession.canAddOutput(dataOutput) {
captureSession.addOutput(dataOutput)
}
captureSession.commitConfiguration()
let queue = DispatchQueue(label: "com.Osmo.captureQueue")
dataOutput.setSampleBufferDelegate(self, queue: queue)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With