ios - 无法让 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
}
}
解决方案
与其尝试从路径中删除所有点并重用路径对象,不如构造一条新路径。
一旦绘制了路径,它就是上下文的一部分,您不能通过更改路径来删除或更改图形。如果要从绘图中删除某些内容,则必须擦除上下文(或其中的一部分)并在已擦除的位置重新绘制。
通常你会擦除所有内容并重新绘制。
您也不应该在 viewDidLoad 中绘图,此时视图甚至可能没有连接到绘图表面。绘图应该由视图完成,而不是视图控制器。
推荐阅读
- search - 核心数据 - 搜索具有给定标识符的单个对象
- rstudio - 使用特定于路径的控制台打开 Rproject
- c# - 如何在 IIS 中部署 web api webhook 发送者?
- kdb - 如何在 KDB 中对键控表进行列索引?
- excel - 如果在各种列中找不到部分字符串,则删除行:VBA
- google-apps-script - 在 Google Apps 脚本中使用 Google People API 删除联系人返回 404 错误
- python - 是否有存储多选值的首选方法?
- next.js - 部署 Vercel 时更改文件名会导致错误
- node.js - 如何从 Express 连接到 Heroku PostgresQL 数据库?
- flutter - 如何从颤动的日历中获取选定的日期