I'm trying to adopt one of my old programs to new SwitUI. I could not find a way to draw the text on a graph. Below example is displaying two lines (in reality it will be some sort of oscilloscope showing real time voltage changes). To keep the story short. below fragment is drawing two lines and then I want to have some description "label" on it.
Lines are drawn correctly but then cannot get any text. UIGraphics is not available on Mac OS applications. For last three days I'm googling a lot. No success :-(
import SwiftUI
import CoreGraphics
struct ContentView: View {
var body: some View {
VStack{
printText(graphWidth: 1.0, amplitude: 0.4).stroke()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct printText: Shape {
let graphWidth: CGFloat
let amplitude: CGFloat
func path(in rect: CGRect) -> Path {
var path = Path()
path.move(to: CGPoint(x: 100, y: 200))
path.addLine(to: CGPoint(x: 200, y: 200))
path.addLine(to: CGPoint(x: 200, y: 300))
let font = NSFont(name: "Helvetica", size: 24.0)
let fontAttributes = [NSAttributedString.Key.font: font]
let attrString = NSMutableAttributedString(string: "TeSt1", attributes: fontAttributes as [NSAttributedString.Key : Any])
attrString.addAttribute(NSAttributedString.Key.foregroundColor,
value: NSColor.red, range: NSRange(location: 0, length: 5))
print(attrString)
attrString.draw(at: CGPoint(x: 100, y: 100))
attrString.draw(at: NSPoint(x: 100, y: 200))
print("rect Dimensions W: \(rect.width), H: \(rect.height)")
attrString.draw(in: rect)
return path
}
}