[英]Draw rectangle with negative coordinates
當我試圖在帶有負坐標(-x和-y)的PictureBox中繪制一個矩形時,矩形會消失,但是當它具有正坐標時,一切都沒問題。 這是代碼:
這里我得到矩形的起始坐標
private void PictureBox1_MouseDown(object sender, MouseEventArgs e)
{
start_point.X = e.X;
start_point.Y = e.Y;
}
在這里我得到矩形的結束坐標:
private void PictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
end_point.X = e.X;
end_point.Y = e.Y;
PictureBox1.Refresh();
}
}
在這里我計算矩形的寬度和高度:
private void PictureBox1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.FillRectangle(sb, start_point.X, start_point.Y, end_point.X - start_point.X, end_point.Y - start_point.Y);
}
如果起點坐標小於終點坐標,則一切正常,但當結束坐標小於起點坐標時,寬度或高度或兩個值均為負值...如何解決此問題?
用戶可以通過4種方式拖動鼠標來制作矩形。 其中只有一個你現在很滿意,從左上角到右下角。 其他3種方式為矩形的寬度或高度產生負值。 你處理所有這四種可能性:
var rc = new Rectangle(
Math.Min(startpoint.x, endpoint.x),
Math.Min(startpoint.y, endpoint.y),
Math.Abs(endpoint.x - startpoint.x),
Math.Abs(endpoint.y - startpoint.y));
e.Graphics.FillRectangle(sb, rc);
如果起始X是<結尾X,則只需在繪制前交換值。 Y坐標也一樣。
if ( start_point.X < end_point.X )
{
var oldX = start_point.X;
start_point.X = end_point.X;
end_point.X = oldX;
}
if ( start_point.Y < end_point.Y )
{
var oldY = start_point.Y;
start_point.Y = end_point.Y;
end_point.Y = oldY;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.