使用鼠标平移/变换移动矩形

本文关键字:变换 移动 鼠标 | 更新日期: 2023-09-27 18:22:16

我需要从csv文件中制作一个线条图,并用GDI绘制它。我有一个Windows窗体,但现在我想更改比例并移动。

我开始做一些更简单的事情,比如用鼠标移动矩形,但总是从原点开始绘制矩形。有人能帮忙吗?

我的代码是:

public partial class Form1 : Form {
    int origenX;
    int origenY;
    bool transformar = false;

    public Form1() {
        InitializeComponent();
    }
    private void Form1_Paint(object sender, PaintEventArgs e) {
        dibujar(e.Graphics);
    }
    private void Form1_MouseMove(object sender, MouseEventArgs e) {
        int deltaX = e.X - origenX;
        int deltaY = e.Y - origenY;
        if (transformar) {
            System.Drawing.Graphics g = this.CreateGraphics();
            Matrix mAux = new Matrix();
            mAux.Translate(deltaX, deltaY);
            g.Transform = mAux;
            dibujar(g);
            g.Dispose();
        }
        this.Text = "x=" + deltaX.ToString() + ", y=" + deltaY.ToString(); 
    }
    private void Form1_MouseDown(object sender, MouseEventArgs e) {
        transformar = true;
        origenX = e.X;
        origenY = e.Y;
    }
    private void Form1_MouseUp(object sender, MouseEventArgs e) {
        transformar = false;
    }
    private void dibujar(System.Drawing.Graphics g) {
        g.Clear(Color.White);
        g.DrawEllipse(new Pen(Color.Blue, 2), new Rectangle(50, 50, 50, 50));
    }
}

使用鼠标平移/变换移动矩形

已经解决了,无论如何都要感谢,代码如下:

public partial class Form2 : Form {
    private float dx=0;
    private float dy=0;
    private float X0=1;
    private float Y0=1;
    private bool trasladar = false;
    public Form2() {
        InitializeComponent();
    }
    private void Form2_Paint(object sender, PaintEventArgs e) {
        e.Graphics.TranslateTransform(dx, dy, MatrixOrder.Append);
        e.Graphics.Clear(Color.White);
        e.Graphics.DrawEllipse(new Pen(Color.Blue), new Rectangle(50, 50, 50, 50));
    }
    private void Form2_MouseDown(object sender, MouseEventArgs e) {
        Cursor = Cursors.SizeAll;
        trasladar = true;
        X0 = e.X;
        Y0 = e.Y;
    }
    private void Form2_MouseUp(object sender, MouseEventArgs e) {
        Cursor = Cursors.Default;
        trasladar = false;
    }
    private void Form2_MouseMove(object sender, MouseEventArgs e) {
        if (trasladar) {
            dx += (e.X - X0);
            dy += (e.Y - Y0);
            X0 = e.X;
            Y0 = e.Y;
            Invalidate();
        }
    }
}

在重新绘制表单时使用this.Invalidate();

它将声明表单无效,因此将强制重新绘制。只有到那时才会调用Form1_Paint

通过在"绘制事件"中执行"调试"输出来测试此行为。然后,您可以开始进一步的调试以获得所需的内容。