MrGreyKnight
MrGreyKnight

Reputation: 37

How to make a draw rectangle 2px larger on each side than the recorded rectangle. C#

Hey so I'm currently using this post to create rectangles on a canvas and was wandering how i could make the drawn rectangle 2px larger than the actual rectangle recorded. Is this possible and if so how would i do this have been trying to work it out for a while now would be really useful to finally have a solution.

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

just for reference this code came from this post

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

Upvotes: 0

Views: 118

Answers (1)

Marco Luzzara
Marco Luzzara

Reputation: 6036

In the getRectangle method you just need to change the values that you use in the constructor for the Rectangle. Since the third one refers to the width property, you add the number of pixels to Math.Abs(startPos.X - currentPos.X).After this the check if (rc.Width > 0) is useless for obvious reasons.

Upvotes: 1

Related Questions