如何在UIView中不断更新绘图

时间:2017-04-26 20:34:05

标签: ios iphone swift asynchronous uiview

我不断从源读取数据(CGFloat数组),我想从该源上的数据点在UIView上画一条线。

据我所知,我需要使用UIBezierPath来创建该行。我最初能够这样做,但我不知道如何继续更新UIView上的绘图[就像一系列path.move(..)]。

有谁知道如何实现这个?

TIA

1 个答案:

答案 0 :(得分:1)

子类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。