如何更新Graphics.DrawLine()点位置?

时间:2018-05-18 20:30:44

标签: c# forms visual-studio graphics draw

我为每个边缘使用Graphics.DrawLine()绘制了一个框。但我希望这个盒子能够自由地在屏幕上移动,同时改变边缘的大小。通过使用中点和宽度和高度创建框,然后使用基本数学来查找线连接的4个点。我的问题是:如何更新线的位置?我是否必须清除图形并重新绘制每帧的线条?任何答案都会有所帮助。谢谢。

以下是我正在使用的代码:

private void Form1_Paint(object sender, PaintEventArgs e)
    {
        Point box_Middle = new Point(300, 300);

        int boxWidth = 100;
        int boxHeight = 200;

        Pen boxPen = new Pen(Color.Red, 3);

        DrawBox(e, boxPen, box_Middle, boxWidth, boxHeight);
    }

    void DrawBox (PaintEventArgs e, Pen pen, Point middle, int width, int height)
    {
        graphics = e.Graphics;
        graphics.TextRenderingHint = System.Drawing.
                                        Text.TextRenderingHint.
                                        SingleBitPerPixelGridFit;

        // Draw Box
        Point topLeft = new Point(middle.X - width / 2, middle.Y - height / 2);
        Point topRight = new Point(topLeft.X + width, topLeft.Y);
        Point bottomLeft = new Point(topLeft.X, topLeft.Y + height);
        Point bottomRight = new Point(topRight.X, bottomLeft.Y);

        graphics.DrawLine(pen, topLeft, topRight);
        graphics.DrawLine(pen, topLeft, bottomLeft);
        graphics.DrawLine(pen, bottomLeft, bottomRight);
        graphics.DrawLine(pen, topRight, bottomRight);
    }

0 个答案:

没有答案