I have a Swift app that includes a barcode scanner, and I am trying to add a box around the barcode after it is scanned. I tried following this to get the bounding box working, but I'm ending up with some weird results. The bounding box does not appear anywhere, but around 20 seconds after scanning the barcode a vertical green line appears, regardless of if the barcode is still in the view or not.
Here are the functions that are handling the barcode scanning and drawing the bounding box:
func barcodeRequestHandler(request: VNRequest, error: Error?) {
guard let results = request.results as? [VNBarcodeObservation],
let payloadStringValue = results.last?.payloadStringValue
else { return }
self.removeMask()
guard let lastResult = results.last else { return }
self.drawBoundingBox(rect: lastResult)
// Other code to parse the actual barcode
}
func drawBoundingBox(rect: VNRectangleObservation) {
let transform = CGAffineTransform(scaleX: 1, y: -1).translatedBy(x: 0, y: -self.previewLayer.frame.height)
let scale = CGAffineTransform.identity.scaledBy(x: self.previewLayer.frame.width, y: self.previewLayer.frame.height)
let bounds = rect.boundingBox.applying(scale).applying(transform)
createLayer(in: bounds)
}
private func createLayer(in rect: CGRect) {
maskLayer = CAShapeLayer()
maskLayer.frame = rect
maskLayer.cornerRadius = 10
maskLayer.opacity = 0.75
maskLayer.borderColor = UIColor.green.cgColor
maskLayer.borderWidth = 5.0
previewLayer.insertSublayer(maskLayer, at: 1)
}
func removeMask() {
maskLayer.removeFromSuperlayer()
}
This is what happens around 20 seconds after scanning the barcode, the vertical green line shows up whether or not the barcode is still in view. The red boxes are part of the barcode image, those aren't from the app. Any idea as to why the bounding box seems to be showing up as a vertical green line, why it would be delayed, or what could be wrong with my current setup?
