我不断地从源读取数据(CGFloat 数组),我想从该源上的数据点在 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")
}
}
}
在您的 View Controller 中创建一个类型为 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。
关于ios - 如何在 UIView 中持续更新绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43644050/