绘制带负坐标的矩形

时间:2013-11-06 22:02:21

标签: c# windows-applications

当我试图在PictureBox中绘制一个带有负坐标(-x和-y)的矩形时,矩形会消失,但是当它具有正坐标时,一切都没问题。这是代码:

这里我得到了矩形的起始坐标

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

如果起点坐标小于终点坐标,则一切正常,但当结束坐标小于起始坐标时,宽度或高度或两个值均为负... 我该如何解决这个问题?

2 个答案:

答案 0 :(得分:11)

用户可以通过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);

答案 1 :(得分:1)

如果起始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;
}
相关问题