So, I have a snapshot of a video source, which I get into an Image, grab a Graphics object for it, and then draw a timestamp in the bottom right of the image. No problem thus far. However, I cannot guarantee what colour is going to be behind the text, so no matter what brush I use, it will almost certainly clash with some of the images that it is drawn on, making the text unreadable.
I am wondering if anyone knows of a way (either a method in .net, or a nice algorithm), for determining the best colour for a string based on the image behind it.
Cheers
just draw the string 5 times.
One time 1(or2) pixels to the left in black
One time 1(or2) pixels to the right in black
One time 1(or2) pixels above it in black
One time 1(or2) pixels below it in black
and the final time in white on the place where you want it
The only reliable way is to use a contrasting outline.
Back in the days of Commodore 64 sprite graphics, if you wanted something to stand out against any background, you used XOR blitting. Some people referred to this as 'reverse video'.
You can draw lines this way using ControlPaint.DrawReversibleLine, but that won't work for text.
This CodeProject article shows how you can create an XOR brush using interop to gdi32.dll.
Or, if it is allowed, you could use a background color (your choice) for the text (for example white text on black background).
Otherwise, you would need to capture the rectangle where the text is written (for every frame), create the negative image of it, and then get the median color in the rectangle and use it to write the text.
A more complex solution would get you to use two layers (initial picture - L1 and Text (transparent background, black text) - L2),
and before combining them, take all the pixels from L2 that contain text and change the color for the each pixel of the text to the "negative" underlying pixel color value of the L1, but you won't get something that's too usable from a "viewer's" point of view.
This could be a number of variations on the answer by reinier.
Draw underlying text (the four offset ones mentioned by reinier) not in black, but actually in a contrasting color to the foreground color of the actualy text.
Draw the text twice: once in a contrasting color but in bold and/or a slightly larger size, then in the text foreground color over that. Might have to fiddle a bit with coordinates and even need to do the drawing per word or even character to get both passes to nicely align and not give an ugly end result.
Do what reinier suggested, but perhaps not four times (all four directions), but maybe three or even two times to get a kind of "shaded" look.
Let go of the whole "draw text pixel by pixel using API calls" approach and use advanced multilayer compositing techniques like the ones available in WPF design.
For some examples of the last option, check out slides 18 and 21 in Advanced OSM Cartography on SlideShare.
The following snippet shows how to invert a color (background) and then applies Dinah's suggestion to create the background using Graphics.DrawString().
private static Color InvertColor(Color c)
{
return Color.FromArgb(255 - c.R, 255 - c.G, 255 - c.B);
}
// In the following, constants and inplace vars can be parameters in your code
const byte ALPHA = 192;
var textColor = Color.Orange;
var textBrush = new SolidBrush(Color.FromArgb(ALPHA, textColor));
var textBrushBkg = new SolidBrush(Color.FromArgb(ALPHA, InvertColor(textColor)));
var font = new Font("Tahoma", 7);
var info = "whatever you wanna write";
var r = new Rectangle(10, 10, 10, 10);
// write the text
using (var g = Graphics.FromImage(yourBitmap))
{
g.Clear(Color.Transparent);
// to avoid bleeding of transparent color, must use SingleBitPerPixelGridFit
g.TextRenderingHint = TextRenderingHint.SingleBitPerPixelGridFit;
// Draw background for text
g.DrawString(info, font, textBrushBkg, r.Left - 1, r.Top - 1);
g.DrawString(info, font, textBrushBkg, r.Left + 1, r.Top + 1);
g.DrawString(info, font, textBrushBkg, r.Left + 1, r.Top - 1);
g.DrawString(info, font, textBrushBkg, r.Left - 1, r.Top + 1);
// Draw text
g.DrawString(info, font, textBrush, r.Left, r.Top);
}
Related
I have a custom WinForms control which could be described as some kind of terminal control (like a control containing Putty). According to this, the control should display a lot of characters, each with a different color and background color (worst case).
Currently I'm using the (kind of obsolete) Graphics.MeasureString method to determine the size of a single character in my fixed-size font so I can calculate the position of a character at a specific row and column. Then I use Graphics.DrawString to draw the characters. To optimize the performance I create a BufferedGraphics and group characters by their properties to draw consecutive characters with the same color with just one DrawString call. (Because one DrawString call per character is really slow.)
Now the problem is that DrawString apparently calculates the width of a character slightly different from MeasureString. When I draw a complete line at once, the resulting text width is different from what I calculated using the width of a single character multiplied by the character count of the line. It's just one or two pixels (or maybe less), but you can see it clearly - especially because I'm using anti-alias so you can even see a difference of just half a pixel.
The following sample code draws a long string a on the form's graphics, followed by character 'B'. Then it draws just a 'B' on the position calculated by measuring a.
var f = new Form {
Width = 1200,
Height = 500,
Font = new Font("Consolas", 11, FontStyle.Regular)
};
f.Paint += delegate(object sender, PaintEventArgs e) {
var a = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
var size = e.Graphics.MeasureString(a, f.Font, new PointF(0, 0), StringFormat.GenericTypographic);
using (var black = new SolidBrush(Color.Black))
{
e.Graphics.DrawString(a + "B", f.Font, black, 0, 0, StringFormat.GenericTypographic);
e.Graphics.DrawString("B", f.Font, black, size.Width, 20, StringFormat.GenericTypographic);
}
};
f.Show();
And if you look closely, you will see that the second B is about one pixel more right - at least with my display settings (100% dpi scale, ClearType enabled). Although one pixel is not much, when you draw lines using unicode characters U+2500 through U+257F it looks pretty ugly if the characters aren't perfectly aligned.
Also I can't use the TextRenderer class because its MeasureString method returns integer values, but DrawString of course does not draw each character on a full pixel position (what would be required to align it with a position calculated using row/column and the measured integer character size).
So my question is: Is there any (efficient) method to draw strings which are perfectly aligned to their corresponding position calculated using the character size?
P.S.: MeasureString with a 200-character-string returns exactly 200 times the return value of MeasureString with a single-character-string.
I have had some similar issues with measuring the strings in Graphics. I have used SizeInPoints, a property from the class Font and multiplied it for the number of characters I have in the string... I dont't know if it helps.
If not it can be a "rounding" problem with the pixels... then I would try to scale up the font size (maybe 10 times), measure it and then divide it by 10 again when using the size to color the background.
I hope it helps.
Good luck! Regards!
I'm having same issue.
It seems that the behavior depends on the font size.
After changing font with following code, this issue didn't occur.
Font = new Font("Consolas", 20.0F, FontStyle.Regular, GraphicsUnit.Pixel)
However, with another font size as below this issue still occurs.
Font = new Font("Consolas", 20.3F, FontStyle.Regular, GraphicsUnit.Pixel)
My guess on background of this issue: MeasureString and DrawString uses different layout routine and they have different characteristic in rounding error of float number. Only with 'simple' font size they gives same results.
Also, this issue didn't occur with bitmap fonts.
I have an image where I need to change the background colour (E.g. changing the background of the example image below to blue).
However, the image is anti-aliased so I cannot simply do a replace of the background colour with a different colour.
One way I have tried is creating a second image that is just the background and changing the colour of that and merging the two images into one, however this does not work as the border between the two images is fuzzy.
Is there any way to do this, or some other way to achieve this that I have no considered?
Example image
Just using GDI+
Image image = Image.FromFile("cloud.png");
Bitmap bmp = new Bitmap(image.Width, image.Height);
using (Graphics g = Graphics.FromImage(bmp)) {
g.Clear(Color.SkyBlue);
g.InterpolationMode = InterpolationMode.NearestNeighbor;
g.PixelOffsetMode = PixelOffsetMode.None;
g.DrawImage(image, Point.Empty);
}
resulted in:
Abstractly
Each pixel in your image is a (R, G, B) vector, where each component is in the range [0, 1]. You want a transform, T, that will convert all of the pixels in your image to a new (R', G', B') under the following constraints:
black should stay black
T(0, 0, 0) = (0, 0, 0)
white should become your chosen color C*
T(1, 1, 1) = C*
A straightforward way to do this is to choose the following transform T:
T(c) = C* .* c (where .* denotes element-wise multiplication)
This is just standard image multiplication.
Concretely
If you're not worried about performance, you can use the (very slow) methods GetPixel and SetPixel on your Bitmap to apply this transform for each pixel in it. If it's not clear how to do this, just say so in a comment and I'll add a detailed explanation for that part.
Comparison
Compare this to the method presented by LarsTech. The method presented here is on the top; the method presented by LarsTech is on the bottom. Notice the undesirable edge effects on the bottom icon (white haze on the edges).
And here is the image difference of the two:
Afterthought
If your source image has a transparent (i.e. transparent-white) background and black foreground (as in your example), then you can simply make your transform T(a, r, g, b) = (a, 0, 0, 0) then draw your image on top of whatever background color you want, as LarsTech suggested.
If it is a uniform colour you want to replace you could convert this to an alpha. I wouldn't like to code it myself!
You could use GIMP's Color To Alpha source code (It's GPL), here's a version of it
P.S. Not sure how to get the latest.
Background removal /replacement, IMO is more art than science, you’ll not find one algorithm fit all solution for this BUT depending on how desperate or interested you are in solving this problem, you may want to consider the following explanation:
Let’s assume you have a color image.
Use your choice of decoding mechanism and generate a gray scale / luminosity image of your color image.
Plot a graph (metaphorically speaking) of numeric value of the pixel(x) vs number of pixels in the image for that value(y). Aka. a luminosity histogram.
Now if your background is large enough (or small), you’d see a part of the graph representing the distribution of a range of pixels which constitute your background. You may want to select a slightly wider range to handle the anti-aliasing (based on a fixed offset that you define if you are dealing with similar images) and call it the luminosity range for your background.
It would make your life easier if you know at least one pixel (sample/median pixel value) out of the range of pixels which defines your background, that way you can ‘look up’ the part of the graph which defines your background.
Once you have the range of luminosity pixels for the background, you may run through the original image pixels, compare their luminosity values with the range you have, if it falls within, replace the pixel in the original image with the desired color, preferably luminosity shifted based on the original pixel and the sample pixel, so that the replaced background looks anti-aliased too.
This is not a perfect solution and there are a lot of scenarios where it might fail / partially fail, but again it would work for the sample image that you had attached with your question.
Also there are a lot of performance improvement opportunities, including GPGPU etc.
Another possible solution would be to use some of the pre-built third party image processing libraries, there are a few open source such as Camellia but I am not sure of what features are provided and how sophisticated they are.
I have problem with drawing string in c#
Here is my code:
Graphic.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
Pen pen = new Pen(brush, 2f);
Font font = new Font("Segoue UI", 15);
graphic.DrawString("2", font, brush, new PointF(0f, 0f));
Previously i created picturebox and i did graphic obiect from it.
The problem is that "2" is not drawing in (0;0) but in (4;5). Event if i turn off AntiAlias is still in (4;5).
I check it by drawing two lines from (0;0) to (200;0) and from (0;0) to (0;200) and according to them i calculated that error in drawing string.
Any ideas why? I need draw string in exactly point.
//Edit
i was also trying set font in this way:
Font font = new Font("Microsoft Sans Serif", 10);
and draw "2" in (0,0), the real position of "2" is (3,3). With drawing "1" error is the same (3;3).
Graphics.DrawString is automatically padding the box it uses to draw strings. The reason is that it's purpose is to draw label texts etc. for controls and therefor is "ready-made" so there is padding around the text.
Microsoft eventually realized that this approach wasn't the best for situations when one needed more accurate text drawing (ie. text editors etc.), and for that reason developed the TextRendered class which wraps GDI instead of GDI+ and give back the "old" more accurate string drawing.
Try:
TextRenderer.DrawText(e.Graphics, "2", font, new Point(0, 0), brush);
You might experience padding even with this, but here you can more reliable compensate for that. Check the link below to see what flags you can use with the method.
Note: if you need to measure text it's important to use the TextRenderer.MeasureText() for this.
For more details, go to:
http://msdn.microsoft.com/en-us/library/system.windows.forms.textrenderer.aspx
Flags:
http://msdn.microsoft.com/en-us/library/w3cdh3zw.aspx
what happens if your "string" has a descending letter, like a g or a j? each font allows for descending parts of letters, so you might need to account for that by looking at the font's metrics
http://msdn.microsoft.com/en-us/library/xwf9s90b.aspx
System.Windows.Forms.TextRenderer.DrawText method renders formatted text with or without left and right padding depending on the value of the flags parameter:
TextFormatFlags.NoPadding - fits the text tightly into the bounding box,
TextFormatFlags.GlyphOverhangPadding - adds some left and right margins,
TextFormatFlags.LeftAndRightPadding - adds even bigger margins.
Now, my question is how can I get the exact amount of padding (left and right) added by DrawText to the text for a given device context, string, font etc?
I've dug into .NET 4 with .NET Reflector and found that TextRenderer calculates "overhang padding" which is 1/6 of the font's height and then multiplies this value to calculate left and right margins using these coefficients:
left 1.0, right 1.5 for TextFormatFlags.GlyphOverhangPadding,
left 2.0, right 2.5 for TextFormatFlags.LeftAndRightPadding.
The resulting values are rounded up and passed to the DrawTextExA or DrawTextExW native API functions. It's difficult to recreate this process because font's height is taken not from System.Drawing.Font but from System.Windows.Forms.Internal.WindowsFont and these classes return different values for the same font. And a lot of other internal BCL classes from the System.Windows.Forms.Internal namespace are involved. Decompiling all of them and reusing their code in my app is not an option, because that would be a serious .NET implementation dependency. That's why I need to know if there is some public API in WinForms or at least which Windows functions I can use to get the values of left and right margins.
Note: I've tried to TextRenderer.MeasureText with and without padding and compare the results but that gave me only the sum of left and right margins and I need them separately.
Note 2: In case you wonder why I need this: I want to draw one string with multiple fonts/colors. That involves calling DrawText once for every uniformly formatted substring with NoPadding option (so that the text doesn't spread) but I also want to add manually normal GlyphOverhangPadding at the very beginning and very end of the whole multi-format text.
The value you need for computing left and right margins is TEXTMETRIC.tmHeight, which is possible to obtain using Win32 API.
However, I found that tmHeight is just a line height of a font in pixels, so these three approaches will give you the same value (you can use whichever you like in your code):
int apiHeight = GetTextMetrics(graphics, font).tmHeight;
int gdiHeight = TextRenderer.MeasureString(...).Height;
int gdipHeight = (int)Math.Ceiling(font.GetHeight(graphics));
To obtain left and right margins, we use the same code as TextRenderer does under the hood:
private const float ItalicPaddingFactor = 0.5f;
...
float overhangPadding = (gdiHeight / 6.0f);
//NOTE: proper margins for TextFormatFlags.LeftAndRightPadding flag
//int leftMargin = (int)Math.Ceiling(overhangPadding);
//int rightMargin = (int)Math.Ceiling(overhangPadding * (2 + ItalicPaddingFactor));
//NOTE: proper margins for TextFormatFlags.GlyphOverhangPadding flag
int leftMargin = (int)Math.Ceiling(overhangPadding);
int rightMargin = (int)Math.Ceiling(overhangPadding * (1 + ItalicPaddingFactor));
Size sizeOverhangPadding = TextRenderer.MeasureText(e.Graphics, "ABC", font, Size.Empty, TextFormatFlags.GlyphOverhangPadding);
Size sizeNoPadding = TextRenderer.MeasureText(e.Graphics, "ABC", font, Size.Empty, TextFormatFlags.NoPadding);
int overallPadding = (sizeOverhangPadding.Width - sizeNoPadding.Width);
Now you can easily check that
(leftMargin + rightMargin) == overallPadding
Just to note:
I needed to solve this problem in order to implement "Search Highlight" feature in a ListView-based control that uses GDI text rendering:
Works like a charm :)
This answer is an excerpt from here - http://www.techyv.com/questions/how-get-exact-text-margins-used-textrenderer#comment-35164
If you have ever wanted a Label or TextBox in Windows Forms that performs a little more like on the web, then you've probably figured out that there's no intuitive way to make a Label or TextBox automatically adjust its height to fit the text it contains. While it may not be intuitive, it's definitely not impossible.
In this example, I'll use a TextBox (you could just as easily use a Label) that is docked to the top of a form.To use this, add aTextBox called MyTextBox to the form, and set Dock to DockStyle.Top. Wire up the Resize event of the TextBox to this event handler.
private void MyTextBox_Resize( object sender, EventArgs e )
{
// Grab a reference to the TextBox
TextBox tb = sender as TextBox;
// Figure out how much space is used for borders, etc.
int chromeHeight = tb.Height - tb.ClientSize.Height;
// Create a proposed size that is very tall, but exact in width.
Size proposedSize = new Size( tb.ClientSize.Width, int.MaxValue );
// Measure the text using the TextRenderer
Size textSize = TextRenderer.MeasureText( tb.Text, tb.Font,
proposedSize, TextFormatFlags.TextBoxControl
| TextFormatFlags.WordBreak );
// Adjust the height to include the text height, chrome height,
// and vertical margin
tb.Height = chromeHeight + textSize.Height
+ tb.Margin.Vertical;
}
If you want to resize the a Label or TextBox that is not docked (for example, one that is in a FlowLayoutPanel or other Panel, or just placed on the form), then you can handle the Form's Resize even instead, and just modify the Control's properties directly.
This might seem (very) crude, but this is the only native implementation I can think of:
DrawText draws to an IDeviceContext, which is implemented by Graphics. Now, we can take advantage of that with the following code:
Bitmap bmp = new Bitmap(....);
Graphics graphic = Graphics.FromImage(bmp);
textRenderer.DrawText(graphic,....);
graphic.Dispose();
With the new Bitmap you can go pixel by pixel and count them by some condition.
Again, this method is very crude and wasteful, but at least it's native....
This is not tested but based on the following sources:
http://msdn.microsoft.com/en-us/library/4ftkekek.aspx
http://msdn.microsoft.com/en-us/library/system.drawing.idevicecontext.aspx
http://msdn.microsoft.com/en-us/library/system.drawing.graphics.aspx
http://www.pcreview.co.uk/forums/graphics-bitmap-t1399954.html
I've done something similar a few years ago, to highlight search results (search pattern appears in bold etc.). My implementation was in DevExpress, so the code might not be relevant. If you think it's of use I can copy it, just need to find that implementation.
In System.Windows.Forms, the class to use would be Graphics. It has a MeasureCharacterRanges() method which accepts a StringFormat (start with GenericTypographic and go from there). It is much more appropriate than TextRenderer for displaying a complete string by chaining parts with different styles, fonts or brushes.
You've gone way further than me with the actual padding measuring. DevExpress's controls gave you the text bounding rectangle to start with so that was done for me.
Here's an article by Pierre Arnaud that came up for me in Google, which touches on this area. Unfortunately the GDI+ "Gory details" link there is broken.
Cheers,
Jonno
The fix is to calculate what MeasureText is going to add:
var formatFlags FormatFlags =
TextFormatFlags.NoPadding |
TextFormatFlags.SingleLine;
int largeWidth = TextRenderer.MeasureText(
" ",
font,
new Size(int.MaxValue, int.MaxValue),
formatFlags
).Width;
int smallWidth = TextRenderer.MeasureText(
" ",
font,
new Size(int.MaxValue, int.MaxValue),
formatFlags
).Width;
int extra = smallWidth - (largeWidth - smallWidth);
We calculate the width of one space and the width of two spaces. Both have the extra width added, so we can extrapolate the extra width that is being added. The added width apparently is always the same, so subtracting extra from every width returned by MeasureText gives the expected results.
I'm looking for a way to display multiple colors in a single C#/.NET label. E.g the label is displaying a series of csv separated values that each take on a color depending on a bucket they fall into. I would prefer not to use multiple labels, as the values are variable length and I don't want to play with dynamic layouts. Is there a native support for this?
There is no native control in .NET that does this. Your best bet is to write your own UserControl (call it RainbowLabel or something). 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.
For rendering the text, your UserControl could split the text on commas and then dynamically load a differently-colored Label for each chunk. A better way, however, would be to render the text directly onto your UserControl using the DrawString and MeasureString methods in the Graphics namespace.
Writing UserControls in .NET is really not difficult, and this kind of unusual problem is exactly what custom UserControls are for.
Update: here's a simple method you can use for rendering the multi-colored text on a 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;
}
}
}
}
Obviously this will break if you have more than 4 comma-delimited elements in your text, but you get the idea. Also, there appears to be a small glitch in MeasureString that makes it return a width that is a couple pixels wider than necessary, so the multi-colored string appears stretched out - you might want to tweak that part.
It should be straightforward to modify this code for a UserControl.
Note: TextRenderer is a better class to use for drawing and measuring strings, since it uses ints. Graphics.DrawString and .MeasureString use floats, so you'll get off-by-a-pixel errors here and there.
Update: Forget about using TextRenderer. It is dog slow.
You could try using a RichTextBox so that you can get multiple colors for the string and then make it read only and remove the border. Change the background color to the same as the Form it is on and you might get away with it.
As an alternative, you might do this as rtf or html in a suitable control (such as WebBrowser). It would probably take a bit more resources that you'd ideally like, but it'll work fairly quickly.
If you are building your Windows app for people with XP and up, you can use WPF. Even if it's a Windows Forms app, you can add a WPF UserControl.
I would then use a Label, and set the "Foreground" property to be a gradient of colors.
Or, in Windows Forms (no WPF), you could just use a "Flow Panel", and then in a for loop add multiple Labels as segments of your sentense... they will all "flow" together as if it was one label.
I'm using colored labels quite often to mark keywords in red color etc.
Like in Phil Wright's answer I use a RichTextBox control, remove the border and set the background color to SystemColors.Control.
To write colored text the control is first cleared and then I use this function to append colored text:
private void rtb_AppendText(Font selfont, Color color, Color bcolor,
string text, RichTextBox box)
{
// append the text to the RichTextBox control
int start = box.TextLength;
box.AppendText(text);
int end = box.TextLength;
// select the new text
box.Select(start, end - start);
// set the attributes of the new text
box.SelectionColor = color;
box.SelectionFont = selfont;
box.SelectionBackColor = bcolor;
// unselect
box.Select(end, 0);
// only required for multi line text to scroll to the end
box.ScrollToCaret();
}
If you want to run this function with "mono" then add a space before every new colored text, or mono will not set new the color correctly. This is not required with .NET
Usage:
myRtb.Text = "";
rtb_AppendText(new Font("Courier New", (float)10),
Color.Red, SystemColors.Control, " my red text", myRtb);
rtb_AppendText(new Font("Courier New", (float)10),
Color.Blue, SystemColors.Control, " followed by blue", myRtb);
Slightly off topic ... You could check also:
generate html color table
model colors in sql
the result
You can simply use multiple labels. Set the font properties you want and then use the left. top and width properties to display the words you want displayed differently. This is assuming you are using windows forms.
Try this,
labelId.Text = "Successfully sent to" + "<a style='color:Blue'> " + name + "</a>";
There is no native support for this; you will either have to use multiple labels or find a 3rd-party control that will provide this functionality.
I don't think so. You should create one yourself.
As per your Question your requirement is simple like
lable.Text = "This color is Red", So it have to display text like this
"The color is" will be in Blue and "Red" will be red color ..
This can be done like this
lable.Text = "<span style='Color:Blue'>" + " The color is " +"</span>" + "<span style='Color:Red'>"Red"</span>"