栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

C#.NET标签中的多种颜色

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C#.NET标签中的多种颜色

.NET中没有本机控件可以执行此操作。最好的选择是编写自己的UserControl(称为RainbowLabel之类的东西)。通常,您将有一个自定义标签控件直接从Label继承,但是由于您无法在一个标签中获得多色文本,因此您只能从UserControl继承。

为了呈现文本,您的UserControl可以将文本分割为逗号,然后为每个块动态加载不同颜色的Label。但是,更好的方法是使用Graphics命名空间中的DrawString和MeasureString方法将文本直接呈现到UserControl上。

在.NET中编写UserControl确实并不困难,而这种不寻常的问题正是自定义UserControl的目的所在。

更新 :这是一种可用于在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; }        }    }}

显然,如果您的文本中包含四个以上以逗号分隔的元素,则此操作会中断,但是您可以理解。另外,在MeasureString中似乎有一个小故障,使它返回的宽度比必要的宽度宽了几个像素,因此,多色的字符串显得有些拉长-
您可能想要调整该部分。

修改UserControl的代码应该很简单。

注意
:TextRenderer是用于绘制和测量字符串的更好的类,因为它使用整数。Graphics.DrawString和.MeasureString使用浮点数,因此到处都会出现逐像素错误。

更新 了使用TextRenderer。狗慢。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/575906.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号