Johnny Johnson Johnny Johnson - 1 year ago 112
C# Question

How to determine whether a Line runs through a Rectangle

In my program, I've got a set of chess squares drawn on panel by a Graphics object (with each Square object having a Rectangle object that defines its bounds). I recently, added a method for drawing lines across some of the squares for emphasis. The problem is: I need to be able to "erase" these lines and it seems the only way of erasing a line it is redrawing the squares "affected" by the line.

I want to ask, assuming a line starts from PointA(x, y) and stops at PointB(x, y), how do I determine the squares on the panel to redraw? Is it best to resolve each line into a series of Points and then, check which Square.Rectangle contains any of the points? If so, how do I do that?

Answer Source

I would imagine you would need to iterate through each of the lines (so keep a record of them), and determine if the lines intersect with the top, right, left, or bottom boundaries of the rectangle. You don't need to do anything with the lines once they're drawn, after all, the line object contains all the information you would need to deduce whether or not the line intersects the rectangle. The one thing I would recommend doing (if you're not already), is store the objects in a collection so you can iterate through them.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download