首页 > 解决方案 > 无法让 Swift UIBezierPath 绘图删除然后更新

问题描述

在我的应用程序中,viewdidLoad() 使用 UIBezierPath 显示绿色 UIBezierPath 绘制的线。
但稍后在程序中,事件回调使用相同的 UIBezierPath 来删除所有点并在绿色旁边显示红线。
但是,它所做的只是在同一位置将绿线变为红色。

最终,我想使用 UIBezierPath 每秒显示一个不断变化的多线图 - 即:删除以前的多线图并每秒显示更新的多线图。

显示绿线的代码..........................

    var sensor_plot_UIBezierPath = UIBezierPath()
var sensor_plot_CAShapeLayer = CAShapeLayer()

override func viewDidLoad() 
{
                sensor_plot_UIBezierPath.move(to: CGPoint(  x: 100, 
                                                            y: 100))
                sensor_plot_UIBezierPath.addLine( to: CGPoint(  x:  200,
                                                                y:  200 ) )
        init_app_display()

        ...start background events...
}

func init_app_display()
{
    sensor_plot_CAShapeLayer.path = sensor_plot_UIBezierPath.cgPath
    sensor_plot_CAShapeLayer.fillColor = UIColor.clear.cgColor       // doesn't matter
    sensor_plot_CAShapeLayer.strokeColor = UIColor.green.cgColor
    sensor_plot_CAShapeLayer.lineWidth = 3.0

    view.layer.addSublayer( sensor_plot_CAShapeLayer )
}

应该在它旁边显示红线的代码.......................
(但实际上在相同位置将初始绿线变为红色 - 第一行旁边没有第二行)

...display_plot_update() is called by event from background thread (specifically, BLE event didUpdateValueFor)

    func display_plot_update()
    {
        DispatchQueue.main.async
        {
            self.sensor_plot_UIBezierPath.removeAllPoints()
            self.sensor_plot_UIBezierPath.move(to: CGPoint(     x: 110, 
                                                                y: 100))
            self.sensor_plot_UIBezierPath.addLine( to: CGPoint(  x:  210,
                                                                 y:  200 ) )
            self.sensor_plot_CAShapeLayer.strokeColor = UIColor.red.cgColor
        }
    }

标签: iosswiftuibezierpath

解决方案


与其尝试从路径中删除所有点并重用路径对象,不如构造一条新路径。

一旦绘制了路径,它就是上下文的一部分,您不能通过更改路径来删除或更改图形。如果要从绘图中删除某些内容,则必须擦除上下文(或其中的一部分)并在已擦除的位置重新绘制。

通常你会擦除所有内容并重新绘制。

您也不应该在 viewDidLoad 中绘图,此时视图甚至可能没有连接到绘图表面。绘图应该由视图完成,而不是视图控制器。


推荐阅读