我正在尝试将我的旧程序之一用于新的SwitUI。我找不到在图形上绘制文本的方法。下面的示例显示两行(实际上,它将是某种示波器,显示实时电压变化)。为了使故事简短。下面的片段绘制了两条线,然后我要在其上添加一些描述“标签”。
线条正确绘制,但是无法获取任何文本。 UIGraphics在Mac OS应用程序上不可用。最近三天,我在谷歌上搜索了很多东西。没有成功:-(
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
}
}