简体   繁体   English

绘制带负坐标的矩形

[英]Draw rectangle with negative coordinates

When i'm trying to draw a rectangle in PictureBox with negative coordinates (-x and -y) the rectangle dissapears, though when it has positive coordinates everything is okay. 当我试图在带有负坐标(-x和-y)的PictureBox中绘制一个矩形时,矩形会消失,但是当它具有正坐标时,一切都没问题。 Here's the code: 这是代码:

Here I get starting coordinates of rectangle 这里我得到矩形的起始坐标

private void PictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    start_point.X = e.X;
    start_point.Y = e.Y;
}

Here I get the ending coordinates of rectangle: 在这里我得到矩形的结束坐标:

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

Here I calculate the rectangles width and height: 在这里我计算矩形的宽度和高度:

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

If the starting point coordinates are smaller than ending ones, everything works just fine, but when the ending coordinates are smaller than starting ones, the width or height or both values are negative... How can I solve this problem? 如果起点坐标小于终点坐标,则一切正常,但当结束坐标小于起点坐标时,宽度或高度或两个值均为负值...如何解决此问题?

There are 4 possible ways for the user to drag the mouse to make the rectangle. 用户可以通过4种方式拖动鼠标来制作矩形。 Only one of them you're happy with right now, from upper-left to lower-right. 其中只有一个你现在很满意,从左上角到右下角。 The other 3 ways produce negative values for the rectangle's Width or Height. 其他3种方式为矩形的宽度或高度产生负值。 You deal with all 4 possibilities like this: 你处理所有这四种可能性:

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

If the starting X is < the ending X, just swap the values before drawing. 如果起始X是<结尾X,则只需在绘制前交换值。 Same for the Y coordinates. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM