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

标签 ios iphone swift asynchronous uiview

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

相关文章:

swift - 如何访问 prepareForSegue 中选定单元格的数据

swift - 升级 Xcode 后 cocoapods 的问题

ios - 有没有办法以编程方式检测 iOS 9 低功耗模式?

ios-从后台状态恢复后保持特定事件 ViewController 的屏幕方向

iphone - 我可以从另一个 View 传递/访问原始数据类型(float、double、int)吗?

iphone - 如何在 iPhone 上本地化 "Timer"

Swift - CollectionView,如何查找 IndexPath 中的第一个和最后一个项目?

ios - Swift:如何在 TableViewCell 中按下按钮时添加带有标签的弹出屏幕

ios - 使用 Swift 的双重格式

c++ - 网络应用程序可以在模拟器中运行,但不能在 iPhone 上运行