winforms、.net 3.5,在用户控件或窗体上绘制字符串、线条等
我做了以下工作:winforms、.net 3.5,在用户控件或窗体上绘制字符串、线条等,winforms,user-controls,drawing,paint,Winforms,User Controls,Drawing,Paint,我做了以下工作: public partial class Form1 : Form { public UserControl uc = new UserControl(); private void Form1_Load(object sender, EventArgs e) { uc.Width = 100; uc.Height = 20; uc.BackColor = Color.White; uc.Paint += new PaintEve
public partial class Form1 : Form
{
public UserControl uc = new UserControl();
private void Form1_Load(object sender, EventArgs e)
{
uc.Width = 100;
uc.Height = 20;
uc.BackColor = Color.White;
uc.Paint += new PaintEventHandler((object s, PaintEventArgs pe) => {
Graphics g = ((UserControl)s).CreateGraphics();
g.DrawString("hello", this.Font, Brushes.Black, 0, 0);
});
uc.Visible = true;
this.Controls.Add(uc);
Bitmap bmp = new Bitmap(uc.Width, uc.Height);
uc.DrawToBitmap(bmp, uc.ClientRectangle);
bmp.Save("c:\\my_image.png", System.Drawing.Imaging.ImageFormat.Png);
}
private void button1_Click(object sender, EventArgs e)
{
Bitmap bmp = new Bitmap(uc.Width, uc.Height);
uc.DrawToBitmap(bmp, uc.ClientRectangle);
bmp.Save("c:\\my_image.png", System.Drawing.Imaging.ImageFormat.Png);
}
}
现在,我看到表单上正确显示了“hello”字符串,但我的_image.png文件只显示空白的白色背景。单击按钮1会得到相同的结果。为什么?而且,如果我在VB.NET中编写上述代码,会发生更令人困惑的事情;单击按钮1时,即使白色背景也消失了;uc的行为就像它是新创建的一样,宽度和高度等于150px。
我遗漏了什么?你的
油漆代码错了。您在PaintEventArgs
中被传递了一个Graphics
对象
您不需要(也不应该)调用CreateGraphics
uc.Paint += new PaintEventHandler((object s, PaintEventArgs pe) => {
pe.Graphics.DrawString("hello", this.Font, Brushes.Black, 0, 0);
});
您正在创建的图像文件可能为空,因为在Load
事件中执行DrawToBitmap
代码时,表单的客户端区域尚未绘制
不过,它应该可以很好地响应按钮的点击。这就提出了一个问题,为什么这两个地方都有代码
很难说你的VB.NET代码有什么问题,因为你没有展示它。但是,最好在表单的构造函数中创建/初始化所有用户控件,而不是响应Load
事件;最初,我试图在不订阅绘画活动的情况下画一条线;这就是为什么我使用CreateGraphics,当我切换到paint event时,我忘记了使用event arg。