【发布时间】:2016-06-08 18:01:59
【问题描述】:
我正在尝试在进度条上绘制一个字符串,如here 和here 所述。进度条位于我的选项卡控件中的一系列选项卡页之一上。
这是我的代码:
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
}
我发现它确实绘制了字符串,但在切换到另一个选项卡并返回后,字符串不再可见/那里。
我什至将 "gr" 切换为 "progressBar1.CreateGraphics()" 并删除了 "using" 语句以查看它是否只是在处理字符串,但即使是:
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)));
我也有同样的问题。
【问题讨论】:
-
anyControl.CreateGraphics() 通常是错误的。这也不例外。永远不要使用
control.CreateGraphics!使用Graphics g = Graphics.FromImage(bmp)或在控件的Paint事件中使用e.Graphics参数绘制到Bitmap bmp中.. -
@TaW,谢谢,我会调查的。你能告诉我为什么会这样吗?另外我想知道为什么这个问题被否决了,我提供了大量的证据、资源、结构合理,并且在提问之前已经尝试了一切。
-
你没有做的是适当的研究。这个问题一直被问到,而且有很多很多答案,所以人们会厌倦一次又一次地看到同样的问题。见here for an explanation
-
您还显示了代码,但没有告诉我们它的位置和调用位置。- 请注意,您显示的两个链接确实使用有问题的代码来获取 Graphics 对象。他们的推理可能是他们不关心持久性,因为进展应该在任何事情侵犯图形之前发生。正如您的标签切换所显示的那样,这在我看来有点过于乐观了..
-
最后一点:当我在这里看到让我水平滚动的代码时,我总是畏缩不前。添加一些换行符和一些空格使其更易于阅读..
标签: c# graphics drawstring