[英]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.