如何使每边比记录的矩形大2px的绘制矩形。 C#

时间:2017-06-12 18:42:08

标签: c# canvas coordinates rectangles

嘿所以我现在正在使用这篇文章在画布上创建矩形并且正在徘徊我如何使绘制的矩形比记录的实际矩形大2px。这是可能的,如果是这样的话,我怎么做这个尝试解决一段时间现在最终有一个解决方案真的很有用。

Point startPos;      // mouse-down position
Point currentPos;    // current mouse position
bool drawing;        // busy drawing
List<Rectangle> rectangles = new List<Rectangle>();  // previous rectangles

private Rectangle getRectangle() {
    return new Rectangle(
        Math.Min(startPos.X, currentPos.X),
        Math.Min(startPos.Y, currentPos.Y),
        Math.Abs(startPos.X - currentPos.X),
        Math.Abs(startPos.Y - currentPos.Y));
}

private void canevas_MouseDown(object sender, MouseEventArgs e) {
    currentPos = startPos = e.Location;
    drawing = true;
}

private void canevas_MouseMove(object sender, MouseEventArgs e) {
    currentPos = e.Location;
    if (drawing) canevas.Invalidate();
}

private void canevas_MouseUp(object sender, MouseEventArgs e) {
    if (drawing) {
        drawing = false;
        var rc = getRectangle();
        if (rc.Width > 0 && rc.Height > 0) rectangles.Add(rc);
        canevas.Invalidate();
    }
}

private void canevas_Paint(object sender, PaintEventArgs e) {
    if (rectangles.Count > 0) e.Graphics.DrawRectangles(Pens.Black, rectangles.ToArray());
    if (drawing) e.Graphics.DrawRectangle(Pens.Red, getRectangle());
}

仅供参考此代码来自此帖

https://stackoverflow.com/questions/4060446/how-to-draw-rectangle-on-mousedown-move-c-sharp

1 个答案:

答案 0 :(得分:1)

getRectangle方法中,您只需要更改Rectangle的构造函数中使用的值。由于第三个引用了width属性,因此您将像素数添加到Math.Abs(startPos.X - currentPos.X)。在此之后,检查if (rc.Width > 0)显然是无用的。