Graphics g = label1.CreateGraphics() 不能画图没反应
admin 发表于 2010-06-16 | 来源:互联网 | 阅读:
- C# code
-
Graphics g = label1.CreateGraphics(); g.Clear(Color.Black); Pen p = new Pen(Color.Red ); g.DrawRectangle(p,0,0,10,10); // g.DrawLine(p, 400, 0, 800, 300);
我在窗口中托了一个label控件,用上面的代码画图,怎么没反应呢,
运行后,控件就一片黑暗
用pant事件就能够画起
这是怎么回事啊??
下面是完整代码
- C# code
-
using System.Data; using System.Drawing; using System.Linq; using System.Threading; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); Graphics g = label1.CreateGraphics(); g.Clear(Color.Black); Pen p = new Pen(Color.Red ); g.DrawRectangle(p,0,0,10,10); // g.DrawLine(p, 400, 0, 800, 300); } } }

构造函数里只是构造Label吧,还没有绘图,在OnPaint事件里才绘图了。所以重写OnPaint才可以重绘图形。LZ可以试试。
接分 *****************************************************************************欢迎使用CSDN论坛专用阅读器 : CSDN Reader(附全部源代码) http://feiyun0112.cnblogs.com/
Label1.Refresh
label1_PaintRefresh
public Form1() { InitializeComponent(); Graphics g = label1.CreateGraphics(); g.Clear(Color.Black); Pen p = new Pen(Color.Red ); g.DrawRectangle(p,0,0,10,10); // g.DrawLine(p, 400, 0, 800, 300); }根据你的代码,你只在窗体构造函数中画了一次,当然不行了,当窗体激活的时候,控件会调用paint事件重画,这个时候因为没有上述的代码,当然就没有任何效果了。这个是必须在Paint事件里执行,当有重绘请求时,自然调用Paint事件里的代码,达到你的要求了。
label 太小了,看不到效果的。C# code
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
g.Clear(Color.Black);
Pen p = new Pen(Color.Red);
g.DrawRectangle(p, 0, 0, 10, 10);
g.DrawLine(p, 400, 0, 800, 300);
//label1.Refresh();
}
private void label1_Paint(object sender, PaintEventArgs e)
{
}
哦 绘图就只能依靠Paint事件 了??