2012-07-10 59 views
2

我只是試圖在鼠標移動事件上繪製一個矩形。我剛剛在MouseDown事件中保存了起始點,而結束點來自Mouse Move。並稱爲paintImage函數。使用鼠標在c#中繪製矩形

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

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

問題是當x2的值小於X1或Y2小於Y1矩形被繪製...任何人都幫我在這

+0

看看這個帖子:http://stackoverflow.com/questions/4164864/what-is-the-proper-way-to-draw-a-line-with-mouse -in-c-sharp我想那裏很簡單 – eyossi 2012-07-10 07:05:06

回答

2

你可以很容易地寫一張支票:

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

這也可以寫成較短的形式:

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

感謝Buddy ... It's Worked ... – 2012-07-10 07:21:37

2

您需要交換的CAS座標E中的寬度變負:

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