在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);
白色面板显示在表单中,但那些线条和字符串的图形不是。
答案 0 :(得分:2)
您需要在OnPaint事件中绘制面板。你不能看到你的绘图,因为在组件刷新之后它们被重绘 - 但你没有。
答案 1 :(得分:2)
此代码将进入表单加载事件
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);
}
答案 2 :(得分:1)
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);
}
}