Removing transparency from color

偶尔善良 提交于 2019-12-23 01:14:26

问题


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);


来源:https://stackoverflow.com/questions/24807182/removing-transparency-from-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!