Hi,
Someone has an idea if we can draw a line between two points with multiple colors i.e. some part of line is red and the rest part is green. Something like that.
Regards
Hi,
Someone has an idea if we can draw a line between two points with multiple colors i.e. some part of line is red and the rest part is green. Something like that.
Regards
This thread already shows the two practical routes: break the line into colored segments (, ) for hard color stops, or use a Paint-based gradient () for smooth transitions. The choice depends on whether you want abrupt color boundaries or a continuous blend. The rest below gives a concise, ready-to-use approach for a smooth multi-stop gradient and a few pitfalls to watch for.
Use Graphics2D with a LinearGradientPaint so the gradient follows the line endpoints; set a stroke for thickness and enable anti-aliasing. Example pattern:
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Point2D p1 = new Point2D.Float(x1, y1);
Point2D p2 = new Point2D.Float(x2, y2);
float[] fractions = {0.0f, 0.5f, 1.0f};
Color[] colors = {Color.RED, Color.YELLOW, Color.GREEN};
LinearGradientPaint lg = new LinearGradientPaint(p1, p2, fractions, colors);
g2.setPaint(lg);
g2.setStroke(new BasicStroke(thickness, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER));
g2.draw(new Line2D.Float(x1, y1, x2, y2));
g2.dispose(); Notes and troubleshooting: map the gradient start/end to the same coordinates used to draw the line so colors align; for very thick strokes consider creating the stroked shape and filling it; stroke caps affect how colors end at the line tips; if your JRE lacks advanced Paints or you need exact, pixel-perfect hard breaks, follow the segmentation approach and draw contiguous sub-lines with distinct Colors.
Jump to Post— Member #46692You gotta write your own class for that.
Some elementary mathematics would help.
Imagine you have a line. It begins at (x1,y1) and ends and (x2,y2)
You just need a way to chop that line into bits and for each of those lines find the (x1,y1) and …
You gotta write your own class for that.
Some elementary mathematics would help.
Imagine you have a line. It begins at (x1,y1) and ends and (x2,y2)
You just need a way to chop that line into bits and for each of those lines find the (x1,y1) and (x2,y2) coordinates changing the colour as you see fit.
You could also use Graphics2D and use a GradientPaint
Or you could just make three seprate lines in a row. Wouldn't that be crazy.
Or you could just make three seprate lines in a row. Wouldn't that be crazy.
Nah my way is more complete.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.