我尝试使用SwiftUI中的Shape视图在每个点处绘制一条带有标记的线。我希望线上的每个CGPoint
处都有一个实心圆。我得到的最接近的方法是在每个点处添加一个圆弧。而不是使用圆弧,我如何在每个点添加Circle()
形状?我对其他方法持开放态度。我唯一的要求是使用SwiftUI并能够与标记交互。
import SwiftUI
struct LineShape: Shape {
let values: [Double]
func path(in rect: CGRect) -> Path {
let xStep = rect.width / CGFloat(values.count - 1)
var path = Path()
path.move(to: CGPoint(x: 0.0, y: (1 - values[0]) * Double(rect.height)))
for i in 1..<values.count {
let pt = CGPoint(x: Double(i) * Double(xStep), y: (1 - values[i]) * Double(rect.height))
path.addLine(to: pt)
path.addArc(center: pt, radius: 8, startAngle: Angle(degrees: 0), endAngle: Angle(degrees: 360), clockwise: false)
}
return path
}
}
struct ContentView: View {
var body: some View {
LineShape(values: [0.2, 0.4, 0.3, 0.8, 0.5])
.stroke(.red, lineWidth: 2.0)
.padding()
.frame(width: 400, height: 300)
}
}
3条答案
按热度按时间9vw9lbht1#
您可以制作两个不同的形状,一个用于线条,一个用于标记,并将它们叠加。然后您还可以单独控制它们的颜色:
vmpqdwk32#
根据以前的帖子和评论,这里是我的解决方案:
首先,需要使用扩展来填充和设置形状笔划:
另一件事是Scaler struct用于进行缩放计算:
现在是时候绘制真实的的图表形状了:
如果有单次迭代循环线点绘制形状,我们可以尝试在某些视图中使用它:
最后预览设置:
中提琴:
nbysray53#
对于图表,您现在可以使用
.symbol(.circle)