我正在尝试使用带有新iPhone Xs Max的单视图应用程序构建自定义相机。参考下面的屏幕截图,可以看出AVCaptureVideoPreviewLayer中显示的视频输出占用的空间小于iPhone x上屏幕的安全区域。如何计算尚未占用的空间?
我怎么知道AVCaptureVideoPreviewLayer占用的空间少于安全区域?好吧,顶部“按钮”的顶部边界固定在安全区域的顶部边界。底部按钮类似地锚定在底部安全区域的底部。但是有很多重叠!
问题:
单视图应用程序的布局:按钮顶部约束
所有其他布局约束:
SWIFT:
class ViewController: UIViewController, UIImagePickerControllerDelegate, AVCaptureVideoDataOutputSampleBufferDelegate {
var previewLayer = AVCaptureVideoPreviewLayer.init()
var captureSession: AVCaptureSession!
var previewFrame = CGRect.init()
var safeAreaFrame: CGRect = CGRect.init()
override func viewDidLoad() {
super.viewDidLoad()
let screenSize = UIScreen.main.bounds
// This is (0.0, 0.0, 414.0, 896.0)
startAVCaptureSession()
}
override func viewDidLayoutSubviews() {
print("viewDidLayoutSubviews ...")
let sAreaFrame = UIApplication.shared.windows[0].safeAreaLayoutGuide.layoutFrame
self.safeAreaFrame = sAreaFrame
// self.safeAreaFrame - This is (0.0, 44.0, 414.0, 818.0)
self.previewLayer.frame = view.bounds // // I have tried self.previewLayer.frame = self.safeAreaFrame
self.previewFrame = previewLayer.frame
}
func startAVCaptureSession() {
print("START CAPTURE SESSION!!")
// Setting Up a Capture Session
self.captureSession = AVCaptureSession()
captureSession.beginConfiguration()
// Configure input
let videoDevice = AVCaptureDevice.default(for: .video)
guard
let videoDeviceInput = try? AVCaptureDeviceInput.init(device: videoDevice!) as AVCaptureInput,
self.captureSession.canAddInput(videoDeviceInput)else {return}
self.captureSession.addInput(videoDeviceInput)
// Capture video output
let videoOutput = AVCaptureVideoDataOutput.init()
guard self.captureSession.canAddOutput(videoOutput) else {return}
videoOutput.setSampleBufferDelegate(self, queue: DispatchQueue.init(label: "videoQueue"))
self.captureSession.addOutput(videoOutput)
// start
self.captureSession.commitConfiguration()
self.captureSession.startRunning()
// Display camera preview
self.previewLayer = AVCaptureVideoPreviewLayer.init(session: self.captureSession)
// Use 'insertSublayer' to enable button to be viewable
view.layer.insertSublayer(self.previewLayer, at: 0)
}
}
答案 0 :(得分:1)
与长宽比有关。如果添加此行,它将正常工作:
self.previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill