简体   繁体   中英

Unable to set transparency using Color.FromArgb (but Color.Transparent works)

The control I want to change to his color is a ToolStripItem. When i use this

 item.BackColor = Color.Black;
 item.ForeColor = Color.Transparent;

It works as expected

在此处输入图片说明

But when i try this

item.BackColor = Color.Black;
item.ForeColor = Color.FromArgb(0, 255, 255, 255);

or this

item.BackColor = Color.White;
item.ForeColor = Color.FromArgb(0, 0, 0, 0);

the alpha component is like completely ignored

在此处输入图片说明

Any idea where the problem might have come from?

Edit : Now i know there the problem is, but i'm still unable to use transparency for text. Some aditional informations : The item i need to change his text color is an ToolStripMenuItem. All the items needs to have a different color, so i can't just use a Renderer for my MenuStrip.

Thanks a lot !

ToolStripRenderer uses TextRenderer.DrawText which uses WindowsGraphics.DrawText ` which uses GDI functions to draw text.

For Color.Transparent it doesn't render anything. For other colors GDI functions ignore the alpha part of ARGB color.

What happens behind the scene?

In the internal implementations in WindowsGraphics.DrawText , you can see there is a specific criteria for not drawing the text if the color is Color.Transparent .

So for Color.Transparent it doesn't draw the text:

if (string.IsNullOrEmpty(text) || foreColor == Color.Transparent) 
{
    return;
}

About Color.FromArgb(0,x,y,z) , since Color.Transparent and Color.FromArgb(0,x,y,z) are not the same, so it tries to draw text when you pass Color.FromArgb(0,x,y,z) . It uses a COLORREF structure to pass to SetTextColor . you will see it always ignores the A value:

When specifying an explicit RGB color, the COLORREF value has the following hexadecimal form:

0x00bbggrr

The low-order byte contains a value for the relative intensity of red; the second byte contains a value for green; and the third byte contains a value for blue. The high-order byte must be zero.

How to draw transparent/semi-transparent text?

If you need transparency support for drawing strings, you can override OnRenderItemText method of the ToolStripRenderer and use Graphics.DrawString instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM