Create different stroke styles on same Path - SwiftUI (Based on value between 0-1 like gradient)
Asked Answered
T

1

6

In SwiftUI Shapes we can make different color strokes by using gradients.

Eg -

@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

Is it possible by any means to do the same for stroke styles?

To create something like this -

enter image description here

Stroke Style 1(Full Line) from 0 to n,

Stroke Style 2(Dashed) from n to 1.

Where n can be any floating number 0<=n<=1

Trapp answered 13/1, 2022 at 3:37 Comment(5)
You are not showing minimal, reproducible lines of code.Copley
What about drawing twice, one with dash$, one with full lines, and use a mask to hide the parts you want?Identity
Tried that.. became too cumbersome.. But will look into it with some other angle..Trapp
Was looking to see if there's some way to avoid drawing twice. But don't think soo..Trapp
Thanks for the followup - I'm in the same situation, trying to avoid double-draw.Alford
K
0

You can use only Gradient to achieve this I think

Kirman answered 10/8, 2023 at 13:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.