在SwiftUI中创建不同的路径描边样式(基于0-1之间的值,如渐变)

6
在SwiftUI中,我们可以使用渐变来制作不同颜色的描边。
例如 -
@ViewBuilder
func lineWithSecondColorStyleFromPositionN() -> some View {
    let n = 0.5
    GeometryReader { gr in
        Path { path in
            path.move(to: CGPoint(x: 0, y: 0))
            path.addLine(to: CGPoint(x: gr.size.width, y: gr.size.height))
        }
        .stroke(
            LinearGradient(stops: [
                Gradient.Stop(color: .red, location: 0),
                Gradient.Stop(color: .red, location: n),
                Gradient.Stop(color: .blue, location: n),
                Gradient.Stop(color: .blue, location: 1)
            ], startPoint: .top, endPoint: .bottom),
            style: StrokeStyle(lineWidth: 10, lineCap: .butt)
        )
    }
    .frame(height: 200)
}

enter image description here

有任何办法可以对笔画样式做同样的事情吗?
创建类似于这样的东西 -

enter image description here

粗略翻译如下:

笔画样式1(实线)从0到n,

笔画样式2(虚线)从n到1。

其中n可以是任何浮点数0<=n<=1


你没有展示出最小、可复现的代码行。 - user17784435
1
画两次,一次用虚线,一次用实线,然后使用遮罩来隐藏你想要隐藏的部分,这样怎么样? - Larme
试过了,变得太麻烦了。不过会从其他角度来看一下。 - Kunal Verma
想看看是否有办法避免重复绘制。 但是我觉得不太可能。 - Kunal Verma
谢谢您的跟进 - 我处于同样的情况,试图避免双重绘制。 - Jens Peter
1个回答

0

我认为你只能使用梯度来实现这个。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接