清除 CAShapeLayer 中的所有内容
Erase all contents from CAShapeLayer
我有一个函数可以在 AVCaptureVideoPreviewLayer 的顶部绘制矩形。这个矩形需要在触发时刷新,并绘制一个新的矩形。最好是从 CAShapeLayer 中删除所有内容,还是只删除该层并添加一个新层?我也不知道该怎么做,但我的尝试如下。
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)
}
您可以通过
删除旧层
oldLayer.removeFromSuperlayer()
然后再添加一个
parentLayer.addSublayer(newLayer)
我认为最好的解决方案是在您的视图出现在屏幕上之前准备好两个层,并通过触发器更改它们。
您可以遍历所有子图层并将其移除。
for sublayer in yourLayer.sublayers ?? [] {
sublayer.removeFromSuperlayer()
}
只需添加新的 addSublayer
:
let newSublayer = CAShapeLayer()
yourLayer.addSublayer(newSublayer)
我有一个函数可以在 AVCaptureVideoPreviewLayer 的顶部绘制矩形。这个矩形需要在触发时刷新,并绘制一个新的矩形。最好是从 CAShapeLayer 中删除所有内容,还是只删除该层并添加一个新层?我也不知道该怎么做,但我的尝试如下。
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)
}
您可以通过
删除旧层oldLayer.removeFromSuperlayer()
然后再添加一个
parentLayer.addSublayer(newLayer)
我认为最好的解决方案是在您的视图出现在屏幕上之前准备好两个层,并通过触发器更改它们。
您可以遍历所有子图层并将其移除。
for sublayer in yourLayer.sublayers ?? [] {
sublayer.removeFromSuperlayer()
}
只需添加新的 addSublayer
:
let newSublayer = CAShapeLayer()
yourLayer.addSublayer(newSublayer)