Removing transparency from color

2019-06-06 06:57发布

问题:

Currently I am using this code to convert my RGB string to a color to set as a the background for a Text Box.

 ColorConverter colorConverter = new ColorConverter();
 colorTextBox1.BackColor = (Color)colorConverter.ConvertFromString(displayColor);

But I get this error when I run this code. when the value of displayColor = "#16776960".

An unhandled exception of type 'System.ArgumentException' occurred in System.Windows.Forms.dll
Additional information: Control does not support transparent background colors.

Any idea on how I can take out transparency from the color?

All I want it to do is make the background of the text box that color.

回答1:

Controls do not support semi-transparent colors, and your hex string has 16 at the beginning, which is the alpha component. To apply the color to a control, you will need to strip the alpha from it.

ColorConverter colorConverter = new ColorConverter();
Color color = (Color)colorConverter.ConvertFromString(displayColor);
color = Color.FromARGB(255, color.R, color.G, color.B);
colorTextBox1.BackColor = color;

You can also simply remove the alpha from the string if it is more than 7 characters long (6 color chars and 1 #)

string hex = "#16776960";
if (hex.Length > 7)
   hex = hex.Remove(1,2);