winforms - Draw Rectangle in c# using Mouse -


I'm just trying to draw a rectangle on mouse movement. I saved the starting point in the mouseDown event and the ending point is with the mouse move. And the color image function was called.

  rectangle REC = new rectangle (x1, y1, x2 - x1, y2 - y1); G.DrawRectangle (Pens.Blue, RE); Starting point = (x1, y1) = endpoint = (x2, y2)   

The problem occurs when the value of x2 is less than x1 or y2 is less than y1, is not rectangular. Anyone can help me on this

You can easily write an inquiry:

  int drawX, drag, width, height; If (x1 & lt; x2) {drawX = x1; Width = x2 - x1; } Other {drawX = x2; Width = x1 - x2; } If (y1 and lt; y2) {drawY = y1; Height = y2 - y1; } And {drag = y2; Height = y1 - y2; } Rectangle RE = new rectangle (draws, draw, width, height); G.DrawRectangle (Pens.Blue, RE);   

It can also be written in small form:

  rectangle REC = new rectangle ((x1 = x2) x1: x2, (y1 Y2: Y1: y2, (x1 and lt; x2)? X2 - x1: x1 - x2, (y1 and lt; y2) y2 - y1: y1 - y2); G.DrawRectangle (Pens.Blue, RE);    

Comments