I have a camera app that records videos. My issue is that the preview layer is not in the correct position of its parent uiview
, which has autolayout
constraints.
After reading existing solutions, I’ve set . videoGravity
to .resizeAspectFill
and the preview layer’s frame to the uiview
.bounds
from the uiviewcontroller
viewDidLayoutSubviews
function. Still running into the same issue and am unsure what to try at this point. Any guidance would be appreciated.
Here is my custom class for the preview view with autolayout constraints set via storyboard:
class CameraPreviewView: UIView {
override static var layerClass: AnyClass {
return AVCaptureVideoPreviewLayer.self
}
var cameraPreviewLayer: AVCaptureVideoPreviewLayer {
return layer as! AVCaptureVideoPreviewLayer
}
var session: AVCaptureSession? {
get { return cameraPreviewLayer.session }
set { cameraPreviewLayer.session = newValue }
}
override func layoutSubviews() {
super.layoutSubviews()
self.cameraPreviewLayer.frame = self.bounds
self.cameraPreviewLayer.videoGravity = .resizeAspectFill
}
func refreshLayout() {
self.setNeedsLayout()
self.layoutIfNeeded()
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
DispatchQueue.main.async {
self.cameraPreviewView.cameraPreviewLayer.frame = self.cameraPreviewView.bounds
self.cameraPreviewView.layoutSubviews()
}
DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
self.runCameraSession()
}
}