要解决AVCaptureVideoPreviewLayer无法在屏幕的两个范围内检测到物体的问题,可以通过以下步骤进行操作:
let screenWidth = UIScreen.main.bounds.width
let screenHeight = UIScreen.main.bounds.height
let range1 = CGRect(x: 0, y: 0, width: screenWidth/2, height: screenHeight)
let range2 = CGRect(x: screenWidth/2, y: 0, width: screenWidth/2, height: screenHeight)
let rangeLayer = CALayer()
rangeLayer.backgroundColor = UIColor.clear.cgColor
rangeLayer.borderColor = UIColor.red.cgColor
rangeLayer.borderWidth = 2.0
previewLayer.addSublayer(rangeLayer)
previewLayer.layer.addSublayer(rangeLayer)
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
// 获取物体位置的代码
// 判断物体位置是否在范围内
if range1.contains(objectPosition) || range2.contains(objectPosition) {
DispatchQueue.main.async {
// 更新范围图层的位置
rangeLayer.frame = range1.contains(objectPosition) ? range1 : range2
}
}
}
通过这样的操作,就可以在AVCaptureVideoPreviewLayer上绘制出两个范围,并检测物体是否在范围内。