.NET 中没有本机控件可以执行此操作。最好的选择是编写自己的 UserControl(将其称为 RainbowLabel 或其他名称)。通常,您会拥有一个直接从 Label 继承的自定义标签控件,但由于您无法在一个标签中获取多色文本,因此您只需从 UserControl 继承。
为了呈现文本,您的用户控件可以用逗号分割文本,然后为每个块动态加载不同颜色的标签。然而,更好的方法是使用 Graphics 命名空间中的 DrawString 和 MeasureString 方法将文本直接渲染到 UserControl 上。
在 .NET 中编写 UserControls 实际上并不困难,而这种不寻常的问题正是自定义 UserControls 的用途。
Update:这里有一个简单的方法,您可以使用它在 PictureBox 上渲染多色文本:
public void RenderRainbowText(string Text, PictureBox pb)
{
// PictureBox needs an image to draw on
pb.Image = new Bitmap(pb.Width, pb.Height);
using (Graphics g = Graphics.FromImage(pb.Image))
{
// create all-white background for drawing
SolidBrush brush = new SolidBrush(Color.White);
g.FillRectangle(brush, 0, 0,
pb.Image.Width, pb.Image.Height);
// draw comma-delimited elements in multiple colors
string[] chunks = Text.Split(',');
brush = new SolidBrush(Color.Black);
SolidBrush[] brushes = new SolidBrush[] {
new SolidBrush(Color.Red),
new SolidBrush(Color.Green),
new SolidBrush(Color.Blue),
new SolidBrush(Color.Purple) };
float x = 0;
for (int i = 0; i < chunks.Length; i++)
{
// draw text in whatever color
g.DrawString(chunks[i], pb.Font, brushes[i], x, 0);
// measure text and advance x
x += (g.MeasureString(chunks[i], pb.Font)).Width;
// draw the comma back in, in black
if (i < (chunks.Length - 1))
{
g.DrawString(",", pb.Font, brush, x, 0);
x += (g.MeasureString(",", pb.Font)).Width;
}
}
}
}
显然,如果文本中的逗号分隔元素超过 4 个,这就会失败,但您明白了。此外,MeasureString 中似乎存在一个小故障,导致它返回的宽度比必要的宽几个像素,因此多色字符串看起来被拉长了 - 您可能需要调整该部分。
修改 UserControl 的此代码应该很简单。
Note:TextRenderer 是一个更好的用于绘制和测量字符串的类,因为它使用整数。 Graphics.DrawString 和 .MeasureString 使用浮点数,因此您会到处出现像素误差。
Update: Forget关于使用 TextRenderer。这是狗慢。