gpt4 book ai didi

ios - 如何在 UIView 中持续更新绘图

转载 作者:行者123 更新时间:2023-11-28 15:41:30 25 4
gpt4 key购买 nike

我不断地从源读取数据(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com