Search code examples
iosswiftcore-graphicscalayercashapelayer

Erase all contents from CAShapeLayer


I have a function that draws rectangles on top a AVCaptureVideoPreviewLayer. This rectangle needs to be refreshed upon a trigger, and a new rectangle drawn. Is it best to erase all contents from the CAShapeLayer or just remove the layer and add a new layer? I don't know how to do either but my attempt is below.

func showRectangle(recLayer: CAShapeLayer, vnRectangleObservation: VNRectangleObservation) -> Void{

    // new CAShapeLayer
    let newLayer = CAShapeLayer.init()

    let rectangle = UIBezierPath.init()
    rectangle.move(to: CGPoint.init(x: vnRectangleObservation.topLeft.x, y: vnRectangleObservation.topLeft.y))
    rectangle.addLine(to: CGPoint.init(x: vnRectangleObservation.topRight.x, y: vnRectangleObservation.topRight.y))
    rectangle.addLine(to: CGPoint.init(x: vnRectangleObservation.bottomRight.x, y: vnRectangleObservation.bottomRight.y))
    rectangle.addLine(to: CGPoint.init(x: vnRectangleObservation.bottomLeft.x, y: vnRectangleObservation.bottomLeft.y))

    rectangle.close()

    newLayer.opacity = 0.4
    newLayer.path = rectangle.cgPath
    newLayer.fillColor = UIColor.orange.cgColor

    // replace current layer containing old rectangle
    recLayer.replaceSublayer(recLayer, with: newLayer)

}

Solution

  • You can iterate through all sublayers and remove them.

    for sublayer in yourLayer.sublayers ?? [] {
        sublayer.removeFromSuperlayer()
    }
    

    And just add new ones with addSublayer:

    let newSublayer = CAShapeLayer()
    yourLayer.addSublayer(newSublayer)