Path questions

Can I change the colour of different segments of a path? For example; this code result in everything being drawn in green but I would have thought (incorrectly it seems) that the rectangle would be red and the line green?

juce::Path p;
g.setColour(juce::Colours::red);
p.addRectangle(getLocalBounds().reduced(2));
g.strokePath(p, juce::PathStrokeType(3));
g.setColour(juce::Colours::green);

p.startNewSubPath(100, 100);
p.lineTo(200, 200);
g.strokePath(p, juce::PathStrokeType(3));
p.closeSubPath();

image

If I can’t achieve what I want above with a single path, I can use two paths:

image

But it seems I can’t have one path appear on top of another?

juce::Path p;
g.setColour(juce::Colours::red);
p.addRectangle(getLocalBounds().reduced(2));
g.strokePath(p, juce::PathStrokeType(3));

g.setColour(juce::Colours::green);
juce::Path p2;
p2.startNewSubPath(0, 0);
p2.lineTo(0, 200);
g.strokePath(p2, juce::PathStrokeType(3));
p2.closeSubPath();

In this case I would expect a green line to appear over the top left part of the red border, but it doesn’t.

image

So obviously I have some misunderstandings about how paths are supposed to work. Any care to enlighten me? :pray:

As you can see, the setColour() acts on the graphics context and not on the path, so there is no way to change the colour of the path halfway through.

In the second example I realise the p2.closeSubPath() occurs AFTER the strokePath(), so it won’t have any effect. I can’t really see, if the green appeared on the left edge. I would expect it to be visible from that snippet.

Thanks @daniel, that clarified things for me.

Indeed it is, albeit a thin sliver of a line…:see_no_evil:

You could also p.clear(); and use the same object.

What you see in the second snippet is the effect of strokes being centered. The rectangle is sized to bounds.reduced(2) and stroked with 3, so its outer edge is 0.5 inside the bounds. The line is stroked at 0, so 1.5 fall outside the bounds and 1.5 inside. To cover the rectangle stroke it should be

p2.startNewSubPath(2, 2);
p2.lineTo(2, 200);

Thanks @kamedin. Path::clear() is the key here!