johnDoe
johnDoe

Reputation: 795

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)

}

Upvotes: 0

Views: 794

Answers (2)

Au Ris
Au Ris

Reputation: 4659

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)

Upvotes: 2

Pavel Gubarev
Pavel Gubarev

Reputation: 89

You can remove your old layer by making

oldLayer.removeFromSuperlayer()

And then add a new one

parentLayer.addSublayer(newLayer)

I think the best solution is to prepare both layers before your view appears on the screen and change them by trigger.

Upvotes: 1

Related Questions