【发布时间】:2016-05-26 21:44:38
【问题描述】:
我创建了一个自定义控件并将其绑定到 Form。我在控件中绘制了图形文本并添加到了表单中。但它没有显示表单。这是我的代码。
//创建自定义控件
public class DrawTextImage : Control
{
public void DrawBox(PaintEventArgs e, Size size)
{
e.Graphics.Clear(Color.White);
int a = 0;
SolidBrush textColor = new SolidBrush(Color.Black);
using (SolidBrush brush = new SolidBrush(Color.Red))
{
e.Graphics.FillRectangle(brush, new Rectangle(a, a, size.Width, size.Height));
e.Graphics.DrawString("Text", Font, textColor, new PointF(50, 50));
}
}
}
//加载Form1
public Form1()
{
InitializeComponent();
DrawTextImage call = new DrawTextImage();
call.Text = "TextControl";
call.Name = "TextContrl";
Size siz = new Size(200, 100);
call.Location = new Point(0, 0);
call.Visible = true;
call.Size = siz;
call.DrawBox(new PaintEventArgs(call.CreateGraphics(), call.ClientRectangle), siz);
this.Controls.Add(call);
}
任何帮助,我做错了什么?
【问题讨论】:
-
现在您的控件只显示一次文本。您应该在控件的
OnPaint方法中进行绘图部分。这是一种重复的方法,就像视频游戏的主循环一样。 -
永远不要使用
control.CreateGraphics!永远不要尝试缓存Graphics对象!使用Graphics g = Graphics.FromImage(bmp)或在控件的Paint事件中使用e.Graphics参数绘制到Bitmap bmp中。