gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:45:26 26 4
gpt4 key购买 nike

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

enter image description here

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

无论如何我可以使用 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 等,因为这会闪烁,但这应该是一个很好的开始示例。

结果:

enter image description here

enter image description here

关于c# - 将文本拆分为 2 种颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17266120/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com