如何在Windows应用程序中的c#中的文本中使用标签的两种颜色 [英] how to use two colors in label for text in c# in Windows Application

查看:56
本文介绍了如何在Windows应用程序中的c#中的文本中使用标签的两种颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有文本的标签:Project .....在此文本中,我需要使用一种颜色的pro并使用另一种颜色的对象...

我在Windows应用程序中需要它.

I have one Label with Text : Project .....In this text i need pro in one color and ject in another color ...

I need this in Windows Application...

推荐答案

.NET中没有本机控件可以执行此操作.最好的选择是编写自己的UserControl.通常,您将有一个自定义标签控件直接从Label继承,但是由于您无法在一个标签中获得多色文本,因此您只需从UserControl继承即可.
There is no native control in .NET that does this. Your best bet is to write your own UserControl. Normally you would have a custom label control inherit directly from Label, but since you can''t get multi-colored text in one label, you would just inherit from UserControl

public void RenderRainbowText(string Text, PictureBox pb)
{
 pb.Image = new Bitmap(pb.Width, pb.Height);
 using (Graphics g = Graphics.FromImage(pb.Image))
 {
    SolidBrush brush = new SolidBrush(Color.White);
    g.FillRectangle(brush, 0, 0,
    pb.Image.Width, pb.Image.Height);
    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++)
    {
     g.DrawString(chunks[i], pb.Font, brushes[i], x, 0);
     x += (g.MeasureString(chunks[i], pb.Font)).Width;
     if (i < (chunks.Length - 1))
     {
        g.DrawString(",", pb.Font, brush, x, 0);
        x += (g.MeasureString(",", pb.Font)).Width;
     }
    }
 }
}


为什么不简单地将其放置在正确对齐的两个单独的标签上?如果情况是文本的拆分位置是动态的,则可以执行以下操作:
1.添加一个FlowLayoutPanel并将两个标签添加到该面板
2.添加一个面板并将两个标签添加到该面板.将"AutoSize"属性设置为true.然后将两个标签停靠在左侧"

这两种方法将允许您在第一个标签上添加/删除文本,并且在移动第二个标签的同时自动调整大小.

希望我不会误会您的问题,这对您有帮助:)
Why not simply place this on two separate labels aligned properly? If it is a case where the split position of the text is dynamic, you can do as following:
1. Add a FlowLayoutPanel and add the two labels to that panel
2. Add a Panel and add the two labels to that panel. Set the "AutoSize" property to true. Then dock the two labels to "left"

These two methods will allow you to add/remove text to the first label and it will automatically re-size while moving the second label along with it.

Hope I did not misunderstand your question and this helps :)


这篇关于如何在Windows应用程序中的c#中的文本中使用标签的两种颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆