如何在AVCaptureVideoPreviewLayer - SWIFT上放置一个矩形

时间:2018-05-15 10:28:45

标签: ios swift avfoundation core-graphics avcapturesession

我有一个AVCaptureVideoPreviewLayer,并希望能够在它上面放置一个矩形图层。我有一个触发器想要在此预览的顶部绘制矩形。到目前为止我的尝试是在下面,但我不知道如何继续。

 var previewLayer = AVCaptureVideoPreviewLayer.init()
 var previewFrame = CGRect.init()

 override func viewDidLoad() {
    super.viewDidLoad()

    // Setting Up a Capture Session
    let captureSession = AVCaptureSession()
    captureSession.beginConfiguration()


    // Configure input
    let videoDevice = AVCaptureDevice.default(for: .video)

    guard
        let videoDeviceInput = try? AVCaptureDeviceInput.init(device: videoDevice!) as AVCaptureInput,
        captureSession.canAddInput(videoDeviceInput)else {return}

    captureSession.addInput(videoDeviceInput)


    // Capture video output
    let videoOutput = AVCaptureVideoDataOutput.init()
    guard captureSession.canAddOutput(videoOutput) else {return}
    videoOutput.setSampleBufferDelegate(self, queue: DispatchQueue.init(label: "videoQueue"))
    captureSession.addOutput(videoOutput)


    // start
    captureSession.commitConfiguration()
    captureSession.startRunning()


    // Display camera preview
    let previewLayer = AVCaptureVideoPreviewLayer.init(session: captureSession)
    view.layer.addSublayer(previewLayer)
    previewLayer.frame = view.frame
    previewFrame = previewLayer.frame

}

我的触发器想要在AVCaptureVideoPreviewLayer上绘制一个矩形:

 let rectangle = UIBezierPath.init()
 rectangle.move(to: CGPoint.init(x: value1, y: value2))
 rectangle.addLine(to: CGPoint.init(x: value3, y: value4))
 rectangle.addLine(to: CGPoint.init(x: value5, y: value6))
 rectangle.addLine(to: CGPoint.init(x: value7, y: value8))

 rectangle.close()
 let rec = CAShapeLayer.init()
 rec.path = rectangle.cgPath
 rec.fillColor = UIColor.orange.cgColor

 rec.frame = self.previewFrame
 self.previewLayer.addSublayer(rec) // Does not work

0 个答案:

没有答案