简体   繁体   中英

Draw Rectangle in c# using Mouse

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

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);

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM