Mac OS X - SwiftUI - how to draw a String (text) together with some path

二次信任 提交于 2020-12-10 05:24:27

问题


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
    }
}

来源:https://stackoverflow.com/questions/58707044/mac-os-x-swiftui-how-to-draw-a-string-text-together-with-some-path

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!