【问题标题】:DrawString custom control text is not displayed in winforms C#DrawString自定义控件文本在winforms C#中不显示
【发布时间】: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 中。

标签: c# winforms c#-4.0


【解决方案1】:

您应该使用控件自己的Paint 事件,而不是您必须手动调用的自定义方法。

public class DrawTextImage : Control
{
    protected override void OnPaint(PaintEventArgs e)
    {
        e.Graphics.Clear(Color.White);
        int a = 0;
        SolidBrush textColor = new SolidBrush(Color.Black);
        using (SolidBrush brush = new SolidBrush(Color.Red))
        {
            //Note:  here you might want to replace the Size parameter with e.Bounds
            e.Graphics.FillRectangle(brush, new Rectangle(a, a, Size.Width, Size.Height));
            e.Graphics.DrawString("Text", Font, textColor, new PointF(50, 50));
        }
    }
}

去掉对DrawBox的调用,没必要。

每当需要重绘控制表面时,Paint 事件就会自动触发。您可以使用控件的Invalidate()Refresh() 方法在代码中自己提出此问题。

【讨论】:

    猜你喜欢
    • 2010-10-29
    • 1970-01-01
    • 1970-01-01
    • 2020-03-29
    • 2010-11-11
    • 1970-01-01
    • 1970-01-01
    • 2015-09-19
    相关资源
    最近更新 更多