2

I am just trying to draw a rectangle on mouse move event . I just saved the starting point in MouseDown Event and Ending Point is from Mouse Move . And called the paintImage Function .

Rectangle rec = new Rectangle (x1,y1,x2 - x1 , y2 - y1);
G.DrawRectangle(Pens.Blue,rec);

Starting Points = (x1,y1)
Ending Points = (x2,y2)

The Problem is When the value of x2 is less than x1 OR y2 is less than y1 the rectangle is not drawing ... Anyone help me on this

Mark Hall
  • 53,938
  • 9
  • 94
  • 111
  • look at this post: http://stackoverflow.com/questions/4164864/what-is-the-proper-way-to-draw-a-line-with-mouse-in-c-sharp i guess that from there it is simple – eyossi Jul 10 '12 at 07:05

2 Answers2

2

You could easily write a check:

int drawX, drawY, width, height;
if (x1 < x2)
{
    drawX = x1;
    width = x2 - x1;
}
else
{
    drawX = x2;
    width = x1 - x2;
}

if (y1 < y2)
{
    drawY = y1;
    height = y2 - y1;
}
else
{
    drawY = y2;
    height = y1 - y2;
}

Rectangle rec = new Rectangle (drawX, drawY, width, height);
G.DrawRectangle(Pens.Blue,rec);

This can also be written in shorter form:

Rectangle rec = new Rectangle ((x1 < x2) ? x1 : x2, (y1 < y2) ? y1 : y2, (x1 < x2) ? x2 - x1 : x1 - x2, (y1 < y2) ? y2 - y1 : y1 - y2);
G.DrawRectangle(Pens.Blue,rec);
Legoless
  • 10,942
  • 7
  • 48
  • 68
2

You need to swap coordinates in case the width becomes negative:

int xpos = (x2-x1 < x1) ? x2 : x1;
int ypos = (y2-y1 < y1) ? y2 : y1;
int width = Math.Abs(x2-x1);
int height = Math.Abs(y2-y1);

G.DrawRectangle(Pens.Blue, new Rectangle(xpos, ypos, width, height));
Thorsten Dittmar
  • 55,956
  • 8
  • 91
  • 139