Skip to main content
 首页 » 编程设计

c#之将文本拆分为 2 种颜色

2024年02月13日14emanlee

我正在用 C# 制作自定义进度条,我想在进度条顶部显示百分比。我需要它,以便当条到达文本时,它会改变颜色。以我在下面制作的图像为例:

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

无论如何我可以使用 GDI 重新创建它吗?

提前致谢, 帕特

请您参考如下方法:

您可以通过覆盖您选择的控件上的绘制来实现,

首先绘制黑色背景和橙色文字

    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 作为覆盖绘制的控件的工作示例(只需将面板添加到窗体)

例子:

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 等,因为这会闪烁,但这应该是一个很好的开始示例。

结果: