我不断从源读取数据(CGFloat数组),并且我想从该数据源上的UIView上绘制一条线。如何不断更新UIView中的绘图
我知道我需要使用UIBezierPath来创建该行。我最初可以这样做,但我不知道如何继续更新UIView上的图形[就像一系列path.move(..)]。
有谁知道如何实现这个?
TIA
我不断从源读取数据(CGFloat数组),并且我想从该数据源上的UIView上绘制一条线。如何不断更新UIView中的绘图
我知道我需要使用UIBezierPath来创建该行。我最初可以这样做,但我不知道如何继续更新UIView上的图形[就像一系列path.move(..)]。
有谁知道如何实现这个?
TIA
子类的UIView并重写draw
RECT方法:
import UIKit
class MyLineView: UIView {
// Edit:add the data to draw
public var lineData : Array<Float>?
override func draw(_ rect: CGRect) {
// Read the values and draw the lines
// using your bezier functions
// Edit: just to test - you can see the new data
if let data = lineData {
print("Redrawing \(data.count) elements")
}
}
}
在视图控制器创建Timer
类型的属性,并开始它在适当的点与期望的帧速率会:
import UIKit
class ViewController: UIViewController {
var animationTimer : Timer?
var myLineView : MyLineView?
**// Edit: add an array of data**
var myData : Array<Float>?
override func viewDidLoad() {
super.viewDidLoad()
self.myLineView = MyLineView(frame: self.view.bounds)
self.view.addSubview(myLineView!)
// Edit: init data
self.myData = Array()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Update the view at roughly 10Hz
animationTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: { (timer) in
//Edit: example update of the data before redrawing
self.myData?.append(Float(1))
self.myLineView!.lineData = self.myData!
self.myLineView!.setNeedsDisplay()
})
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// Stop updating
animationTimer!.invalidate()
animationTimer = nil
}
}
这将以近似10Hz的频率调用子类的drawRect。
我看到你调用了setNeedDisplay(),但我该如何操作自定义UIView中的贝塞尔路径? – GonnaGetGet
我已更新我的答案以显示将数据传输到视图。使用你已经使用的代码来绘制起始行,只需扩展它即可在每一帧重新绘制整个数据集。 – norders
标记为答案,因为'self.myLineView!.lineData = self.myData!'帮助了我。我的数据拉在另一个线程上,所以我必须在'DispatchQueue.main.async {}'内部放置'self.myLineView!.setNeedsDisplay()'。谢谢! – GonnaGetGet
一些想法。首先,由于您希望更新UI,因此您需要主线程来完成此操作。接下来,你能解释什么*“连续阅读数据”*的意思?该CGFloat阵列上的一些代码将有所帮助。最后,你最终可能会搞砸东西 - 就像在不断更新中一样。最快的方法是(1)读取数组中的所有数据,同时(2)向用户提供一些反馈,然后(3)建立你的Bezier路径,然后(4)动画绘制它。 – dfd
@dfd我将从麦克风中获取花车,并且我想要实时绘制/绘制这些点。 – GonnaGetGet