如何使用TryParseHtmlString将十六进制转换为Color(RGBA) [英] How to convert hex to Color(RGBA) with TryParseHtmlString
问题描述
如何使用十六进制值更改Unity中的按钮颜色?
我试过了,但是没用,也许我在这里犯了一个错误:
How can I change the button color in Unity, using HEX values?
I tried this, but it doesn't work, perhaps I made a mistake here:
btn.image.color = ColorUtility.TryParseHtmlString(DADADAFF, out color);
推荐答案
您正在将bool分配给Color(btn.image.color
).
You are assigning bool to Color(btn.image.color
).
ColorUtility.TryParseHtmlString
返回bool
而不是Color
.您在第二个参数中获得了输出颜色,然后将其指定给Button
.仅当ColorUtility.TryParseHtmlString
返回true时才使用输出颜色.
ColorUtility.TryParseHtmlString
returns bool
not Color
if successful. You get the output color in the second parameter then take that and assign it to the Button
. Only use the output color if ColorUtility.TryParseHtmlString
returns true.
以下是该代码的外观:
string htmlValue = "#FF0000";
Button btn = GetComponent<Button>();
Color newCol;
if (ColorUtility.TryParseHtmlString(htmlValue, out newCol))
{
btn.image.color = newCol;
}
要将颜色"转换回十六进制:
To convert the Color back to hex:
Color newCol = Color.red;
string htmlValue = ColorUtility.ToHtmlStringRGBA(newCol);
因此,无法在不检查十六进制颜色的情况下分配它 可以先转换为RGB吗?
So there is no way to just assign Hex color without checking that it can be converted to RGB first?
有.删除if
语句.
ColorUtility.TryParseHtmlString(htmlValue, out newCol);
btn.image.color = newCol;
请勿执行此操作,因为您的Color
结果可能是错误的.您应该像在第一个代码中一样使用if
语句来处理此问题.
Don't do this as your Color
result may be wrong. You should handle this with the if
statement like I did in the first code.
这篇关于如何使用TryParseHtmlString将十六进制转换为Color(RGBA)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!