1

我需要从 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));
    }
}
4

2 回答 2

2

已经解决了,谢谢,代码如下:

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();
        }
    }
}
于 2013-07-17T10:27:44.527 回答
0

this.Invalidate();在表单应该重绘时使用。

它将声明表单无效,因此将被迫重绘。只有这样Form1_Paint才会被调用。

通过在 Paint-Event 中执行调试输出来测试此行为。然后你可以开始进一步调试以获得你想要的。

于 2013-07-13T16:30:56.410 回答