2013-06-23 71 views
1

我在C#中创建了一个自定义进度条,并且我想在该栏上显示百分比。我需要它,以便当栏到达文本时,它会改变颜色。就拿我做下面的图片:将文本拆分为2种颜色

enter image description here

假装左侧的橙色矩形是进度条,黑色矩形是空白。

无论如何,我可以重新创建这个使用GDI?

由于提前, 帕特

+0

可以应用效果的图像,它似乎是一个不错的进度条:),请参阅[这里](http://blog.csharphelper.com /2010/08/28/display-unique-progress-bars-in-c.aspx)怎么样。 – MineScript

回答

4

您可以通过您所选择的控制覆盖漆做,

先画出黑色的背景和橙色文本

e.Graphics.FillRectangle(Brushes.Black, panel1.ClientRectangle); 
    e.Graphics.DrawString("StackOverflow", Font, Brushes.Orange, panel1.ClientRectangle); 

然后绘制重叠并剪辑到进度值的大小

var clipRect = new Rectangle(0, 0, (panel1.Width/100) * _progress, panel1.Height); 
    e.Graphics.SetClip(clipRect); 
    e.Graphics.FillRectangle(Brushes.Orange, clipRect); 
    e.Graphics.DrawString("StackOverflow", Font, Brushes.Black, 0, 0); 

这是使用Panel作为控制覆盖油漆(只是一个面板添加至Form)

示例工作示例:

public partial class Form1 : Form 
{ 
    private Timer _progresstimer = new Timer(); 
    private int _progress = 0; 

    public Form1() 
    { 
     InitializeComponent(); 
     panel1.Paint += new PaintEventHandler(panel1_Paint); 
     _progresstimer.Interval = 250; 
     _progresstimer.Tick += (s, e) => 
     { 
      if (_progress < 100) 
      { 
       _progress++; 
       panel1.Invalidate(); 
       return; 
      } 
      _progress = 0; 
      panel1.Invalidate(); 
     }; 
     _progresstimer.Start(); 
    } 



    void panel1_Paint(object sender, PaintEventArgs e) 
    { 
     e.Graphics.FillRectangle(Brushes.Black, panel1.ClientRectangle); 
     e.Graphics.DrawString("StackOverflow", Font, Brushes.Orange, panel1.ClientRectangle); 

     var clipRect = new Rectangle(0, 0, (panel1.Width/100) * _progress, panel1.Height); 
     e.Graphics.SetClip(clipRect); 
     e.Graphics.FillRectangle(Brushes.Orange, clipRect); 
     e.Graphics.DrawString("StackOverflow", Font, Brushes.Black, 0, 0); 
    } 
} 

您将要设置DoubleBuffering等,因为这会闪烁无,但这应该是一个很好的例子。

结果:

enter image description here

enter image description here

+0

非常感谢! 它的作品非常好:) – Pat

+0

@Pat欢迎来到[so]。每个答案旁边都有一个全息复选框。标记正确的答案会给你几点意见,并让每个人都知道你的问题已经解决,并且可以让人们免于进一步的故障排除。祝你好运! –

+0

谢谢,我在找那:) – Pat