DrawString图形消失了

时间:2016-06-07 21:52:33

标签: c# graphics drawstring

我正在尝试按照概述herehere在进度条上绘制字符串。进度条位于我的选项卡控件中的一系列选项卡页面之一。

这是我的代码:

int percent = 55;
using (Graphics gr = progressBar1.CreateGraphics())
{
gr.DrawString(percent.ToString() + "%",
SystemFonts.DefaultFont,
Brushes.Black,
new PointF(progressBar1.Width / 2 - (gr.MeasureString(percent.ToString() + "%", SystemFonts.DefaultFont).Width / 2.0F), progressBar1.Height / 2 - (gr.MeasureString(percent.ToString() + "%", SystemFonts.DefaultFont).Height / 2.0F)));
}

它不起作用。摆弄计时器后:

this.timer1.Enabled = true;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);

private void timer1_Tick(object sender, EventArgs e)
{
    progressBar1.PerformStep();
    System.Threading.Thread.Sleep(100);
    progressBar1.Refresh();
    int percent = (int)(((double)(progressBar1.Value - progressBar1.Minimum) / (double)(progressBar1.Maximum - progressBar1.Minimum)) * 100);
    progressBar1.CreateGraphics().DrawString(percent.ToString() + "%", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
}

只是一些简单的事情:

private void button1_Click(object sender, EventArgs e)
{
    DrawProgress(); //this just calls the a method to do the DrawString
}

我发现它确实绘制了字符串,但在切换到另一个标签后,字符串不再可见/那里。

我甚至改变了#34; gr" to" progressBar1.CreateGraphics()"并删除"使用"声明是否只是处理字符串,但即使是:

progressBar1.CreateGraphics().DrawString(percent.ToString() + "%", SystemFonts.DefaultFont, Brushes.Black, new PointF(progressBar1.Width / 2 - (progressBar1.CreateGraphics().MeasureString(percent.ToString() + "%", SystemFonts.DefaultFont).Width / 2.0F), progressBar1.Height / 2 - (progressBar1.CreateGraphics().MeasureString(percent.ToString() + "%", SystemFonts.DefaultFont).Height / 2.0F)));

我有同样的问题。

1 个答案:

答案 0 :(得分:2)

我认为,最好的解决方案是:您应该从ProgressBar派生并实现自己的Paint处理程序。

以下是一个例子:(已测试)

// Custom paint progressbar
public class ProgressBarWithTitle : ProgressBar
{
    private Brush _barBrush;


    public ProgressBarWithTitle()
    {
        this.SetStyle(ControlStyles.UserPaint, true);
        this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);

        _barBrush = new SolidBrush(this.ForeColor);

    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        var rect = new RectangleF(0, 0, (float)(this.Width * (Value - Minimum) / Maximum), this.Height);
        e.Graphics.FillRectangle(_barBrush, rect);

        var valueString = base.Value.ToString() + "%";

        var textSize = e.Graphics.MeasureString(valueString, SystemFonts.DefaultFont);

        e.Graphics.DrawString(
            valueString,
            SystemFonts.DefaultFont,
            Brushes.Black,
            new PointF(
                (Width / 2) - ((int)textSize.Width / 2),
                (Height / 2) - ((int)textSize.Height / 2)));
    }


}

唯一的问题是,您必须自己绘制进度条。