用GDI画线-Invalidate()/onPaint问题 [英] Drawing lines with GDI - Invalidate() / onPaint problem

查看:62
本文介绍了用GDI画线-Invalidate()/onPaint问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在学习如何使用GDI,但在理解Invalidate()的方式和覆盖onPaint事件的工作上却遇到了困难,并且似乎正在绕圈转圈.

I've been learning how to use GDI but am having difficulty understanding how Invalidate() and overriding the onPaint event work and seem to be going round in circles.

我有以下代码

private void DrawLine()
{
     System.Drawing.Pen myPen = new System.Drawing.Pen(System.Drawing.Color.Red);
     System.Drawing.Graphics formGraphics;
     formGraphics = this.CreateGraphics();
     formGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
     formGraphics.DrawLine(myPen, mouseDown.X, mouseDown.Y, mouseUp.X, mouseUp.Y);
     myPen.Dispose();
     formGraphics.Dispose();
}

protected override void OnPaint(PaintEventArgs e)
{
     DrawLine();
}

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
     mouseDown = e.Location;

}

private void Form1_MouseUp(object sender, MouseEventArgs e)
{
     mouseUp = e.Location;           
}

但是,我可以获得刚才绘制的行的唯一方法是手动调用Invalidate(),并在执行此操作时清除之前的所有行.有人可以告诉我我要怎么做吗?

However, the only way I can get the line I've just drawn to appear is to call Invalidate() manually, and when I do it clears any previous lines. Can anyone tell me where I'm going wrong with this please?

推荐答案

将其更改为此:

Bitmap bmp = new Bitmap(256, 256);

protected override void OnPaint(PaintEventArgs e)
{
  e.Graphics.DrawImage(bmp, new Point(0, 0));
}

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
  mouseDown = e.Location;
}

private void Form1_MouseUp(object sender, MouseEventArgs e)
{
   mouseUp = e.Location;
   using (Graphics g = Graphics.FromImage(bmp))
   {
     g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
     g.DrawLine(Pens.Red, mouseDown.X, mouseDown.Y, mouseUp.X, mouseUp.Y);
   }
   this.Invalidate();           
}

OnPaint方法提供用于绘制的图形画布.实际上,很少有人需要自己调用CreateGraphics.在MouseUp上的Invalidate()调用告诉您的控件调用OnPaint事件.

The OnPaint method provides the graphic canvas that you use to draw. Very rarely, in fact, do you ever need to call CreateGraphics yourself. The Invalidate() call on MouseUp tells your control to call the OnPaint event.

这篇关于用GDI画线-Invalidate()/onPaint问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆