使用translate / transform使用鼠标移动矩形

时间:2013-07-13 14:47:37

标签: c# gdi+ mousemove

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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

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

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

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