在Winform中在面板上绘图时出现问题
本文关键字:问题 绘图 Winform | 更新日期: 2023-09-27 18:03:50
在Form Load的事件处理程序中,我有以下代码
Panel pHText = new Panel();
Font myFont = new Font("Arial", 14);
pHText.Location=new Point(10,10);
pHText.Size=new Size(200,200);
pHText.BackColor = Color.White;
Graphics g = pHText.CreateGraphics();
g.DrawLine(new Pen(Color.Black), 0, 0, 10, 10);
g.DrawString("text", myFont, Brushes.Blue, 10, 10);
Controls.Add(pHText);
表单中显示白色面板,但不显示线条和字符串。
这段代码将在您的表单加载事件
Panel pHText = new Panel();
pHText.Name = "ctrId"; //specify control name, to access it in other parts of your code
pHText.Location = new Point(10, 10);
pHText.Size = new Size(200, 200);
pHText.BackColor = Color.White;
pHText.Paint += paintingUrCtr;//adding onpaint event
Controls.Add(pHText)
添加命名为paintingUrCtr
的油漆事件
private void paintingUrCtr(object sender, PaintEventArgs e)
{
Font myFont = new Font("Arial", 14);
e.Graphics.DrawLine(new Pen(Color.Black), 0, 0, 10, 10);
e.Graphics.DrawString("text", myFont, Brushes.Blue, 10, 10);
}
你需要在OnPaint事件中绘制面板。你不能看到你的绘图,因为组件刷新后,他们被重新绘制-但你不。
FormLoad是绘制图形的错误位置。尝试使用OnPaint方法重载和e.Graphics。
protected override void OnPaint(PaintEventArgs e)
{
// If there is an image and it has a location,
// paint it when the Form is repainted.
base.OnPaint(e);
if(this.picture != null && this.pictureLocation != Point.Empty)
{
e.Graphics.DrawImage(this.picture, this.pictureLocation);
}
}