绘制带负坐标的矩形

use*_*453 6 c# windows-applications

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

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

private void PictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    start_point.X = e.X;
    start_point.Y = e.Y;
}
Run Code Online (Sandbox Code Playgroud)

在这里我得到矩形的结束坐标:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里我计算矩形的宽度和高度:

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);
}
Run Code Online (Sandbox Code Playgroud)

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

Han*_*ant 13

用户可以通过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);
Run Code Online (Sandbox Code Playgroud)


Dav*_*vid 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;
}
Run Code Online (Sandbox Code Playgroud)