How to Draw a Line

I became a bit intimidated and frustrated with my simulation framework so I set it aside for a while. I played a lot of video games and I practiced my piping. I’m bored with the video games, though, and last night I came back to the sim. I’ve got some ideas for making the problems tractable or even non-issues, and that’s the benefit of walking away for a bit. Before tackling the big structure, though, I thought I’d take a look at a small fix: how to tell what direction a link is going.

A link between two components is a directional line. It takes messages from the source end and sends them to the destination end. But if I’m drawing the link as just a blue line, how can you tell by looking which end is which? I thought I’d maybe color the line as a gradient. (First I thought maybe I’d draw little arrows on the line, but that seemed too fiddly for almost bedtime.) The documentation and tutorials around using LinearGradient are all about using gradients as fill for shapes, not about lines, so there was some experimentation along the lines of, “What happens when the source endpoint is to the right of the destination endpoint, or what if the source is below the destination?”

Anyway, this works:

Stop[] stops = new Stop[] {new Stop(source.getX() < dest.getX() ? 0 : 1, Color.BLUE),
                           new Stop(source.getX() < dest.getX() ? 1 : 0, Color.RED)};
LinearGradient linkStroke = new LinearGradient(0, 0, 1, 0, true, CycleMethod.NO_CYCLE, stops);
ctx.setStroke(linkStroke);

Published by pirateguillermo

I play the bagpipes. I program computers. I support my family in their various endeavors, and I enjoy my wonderful life.

Leave a Reply Cancel reply