Reputation: 53
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)
}
Upvotes: 5
Views: 4480
Reputation: 2044
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
}
Upvotes: 7
Reputation: 1441
Try following piece of code :
if let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) {
previewLayer.bounds = view.bounds
previewLayer.position = CGPoint(x: view.bounds.midX, y: view.bounds.midY) //CGPointMake(view.bounds.midX, view.bounds.midY)
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
let cameraPreview = UIView(frame: CGRect(x: 0.0, y: 0.0, width: view.bounds.width, height: view.bounds.height));
cameraPreview.tag = 44221007
cameraPreview.layer.addSublayer(previewLayer)
//cameraPreview.addGestureRecognizer(UITapGestureRecognizer(target: self, action:Selector(("saveToCamera:"))))
view.addSubview(cameraPreview)
self.view.sendSubview(toBack: cameraPreview);
}
Upvotes: 0
Reputation: 9818
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)
}
Upvotes: 3