A
A
Alexander Prokopenko2022-01-24 15:43:00
C++ / C#
Alexander Prokopenko, 2022-01-24 15:43:00

Why is the Win Forms square drawn incorrectly?

Good afternoon. In general, I do Paint on win forms. I made pencil drawing and rectangles, but when I add an image to the picturebox and move it or stretch it, the rectangle is drawn on correctly.
Here is my code:

void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    isLMBclicked = true;

    if (mode == "rectangle")
    {
        point1 = new Point(e.X, e.Y);
        rec.Location = e.Location;
        newRectangle.FlatStyle = FlatStyle.Flat;
        newRectangle.FlatAppearance.BorderColor = pen.Color;
        newRectangle.FlatAppearance.BorderSize = trackBar1.Value;
    }
}

void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
    isLMBclicked = false;
    if (mode == "pen")
    {
        arrayPoints.resetPoint();
    }
    else if (mode == "rectangle")
    {
        graphics.DrawRectangle(pen, rec);
        pictureBox1.Image = map;
        rec = new Rectangle();

        newRectangle.Visible = false;
    }
}

void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    if (!isLMBclicked) { return; }

    if (mode == "pen")
    {
        arrayPoints.setPoint(e.X, e.Y);

        if (arrayPoints.GetCountPoint() >= 2)
        {
            graphics.DrawLines(pen, arrayPoints.GetPoints());
            pictureBox1.Image = map;
            arrayPoints.setPoint(e.X, e.Y);
        }
    }
    else if (mode == "rectangle")
    {
        point2 = new Point(e.X, e.Y);
        if (point2.X > rec.Location.X && point2.Y > rec.Location.Y)
        {
            newRectangle.Visible = true;
            //newRectangle.BackColor = pen.Color;
            var newSize = new Size(point2.X - rec.Location.X, point2.Y - rec.Location.Y);

            if (MouseButtons == MouseButtons.Left)
                if (newSize.Width > 5 && newSize.Height > 5)
                {
                    rec.Size = newSize;

                    newRectangle.Location = new Point(point1.X, point1.Y);
                    newRectangle.Size = newSize;
                    Invalidate();
                }
        }
    }
}


So it is necessary:
61ee9e7b145ab548328573.jpeg

​​And it turns out like this:
61ee9e911d8c5216445732.jpeg

That is, the cursor is in one place, and the square is in another, but when I release the LMB, it gets to the right place

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question