Epaga Epaga - 3 months ago 32
Java Question

Most elegant way to clip a line?

I have a Rectangle2D and a Line2D. I want to "clip" the line so that only the part of the line which is within the rectangle remains. If none of the line is within the rectangle I want the line to be set to (0,0,0,0). Basically something along the lines of a

Rectangle2D.intersect(Line2D src, Line2D dest)

or something similar.

Is there a way to do this with the java.awt.geom API? Or an elegant way to code it "by hand"?


Well, I ended up doing it myself.

For those intereseted, I ended up solving it by turning the line into a rectangle (with getBounds), then using Rectangle.intersect(clipRect,lineRect,intersectLineRect) to create the intersection, then turning the intersection back into a line.