Draw CGContext into Canvas in SwiftUI

32 Views Asked by At

I am trying to drawing a CGContext into a Canvas using swiftUi. First I initialized a CGContext in ContextViewModel class. Then created a timer and timer call addLine() function in every second. In addLine() function, it addLines to CGContext.

import Foundation
import SwiftUI

public class ContextViewModel : ObservableObject{

    var cgContext = CGContext(data: nil,
                              width: 200,
                              height: 200,
                              bitsPerComponent: 8,
                              bytesPerRow: 200 * 4,
                              space: CGColorSpace(name: CGColorSpace.sRGB)!,
                              bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue )

    init()
    {
        createRefreshTimer()
    }

    internal func createRefreshTimer(){
        let _ = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(refreshTick), userInfo: nil, repeats: true)
    }

    @objc internal func refreshTick(){
        addLine()
    }

    func addLine(){

        var randomVal = Int.random(in: 1...100)

        cgContext?.move(to: CGPoint(x: randomVal, y: randomVal))
        cgContext?.addLine(to: CGPoint(x: randomVal+20, y: randomVal))
        cgContext?.addLine(to: CGPoint(x: randomVal+20, y: randomVal+20))
        cgContext?.addLine(to: CGPoint(x: randomVal, y: randomVal+20))
        cgContext?.addLine(to: CGPoint(x: randomVal, y: randomVal))
        cgContext?.setLineWidth(1)
        cgContext?.setStrokeColor(.white)
        cgContext?.strokePath()

    }

}

I want to draw above CGContext into a SwiftUI canvas and display it.

0

There are 0 best solutions below