0

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?

codebro
  • 25
  • 9
  • do you already have the coordinates of the squares stored somewhere? – Rufus L Oct 03 '17 at 00:16
  • 1
    Possible duplicate of [How to know if a line intersects a rectangle](https://stackoverflow.com/questions/5514366/how-to-know-if-a-line-intersects-a-rectangle) – Rufus L Oct 03 '17 at 00:30
  • Not c# but https://www.openprocessing.org/sketch/454672 – PrincePolka Oct 03 '17 at 00:32
  • Too much work. Why not repaint _all_ the rectangles? You don't need to write code and spend extra CPU cycles to find out which rectangles need to be redrawn. – kennyzx Oct 03 '17 at 00:42
  • Maybe, I'll do just that @kennyzx – codebro Oct 03 '17 at 00:47
  • @JohnnyJohnson yeah, just call Invalidate method on the Panel, it will repaint itself, and all the lines you drawn with Graphics.DrawLine method will be gone. – kennyzx Oct 03 '17 at 00:49

2 Answers2

0

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.

Ingenioushax
  • 718
  • 5
  • 20
0

Chessboard cells are joined together, so you don't need to check for all cells. Just traverse along line and get cells touched. Note that this process slightly differs from line rasterizing.

You need to calculate the first cell containing line start point and then get neighbor cells intersected by line one-by-one. For example, if line direction is right-up, then check right and top edges and so on.

If you are aware of effectiveness (large grid), consider quite effective algorithm of Amanatides and Woo

MBo
  • 77,366
  • 5
  • 53
  • 86