如何使用 TryParseHtmlString 将十六进制转换为颜色(RGBA) [英] How to convert hex to Color(RGBA) with TryParseHtmlString

查看:60
本文介绍了如何使用 TryParseHtmlString 将十六进制转换为颜色(RGBA)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用十六进制值更改 Unity 中的按钮颜色?
我试过这个,但它不起作用,也许我在这里犯了一个错误:

btn.image.color = ColorUtility.TryParseHtmlString(DADADAFF, out color);

解决方案

您正在将 bool 分配给 Color(btn.image.color).

如果成功,

ColorUtility.TryParseHtmlString 返回 bool 而不是 Color.您在第二个参数中获得输出颜色,然后将其分配给 Button.仅当 ColorUtility.TryParseHtmlString 返回 true 时才使用输出颜色.

下面是代码的样子:

string htmlValue = "#FF0000";按钮 btn = GetComponent

<小时>

要将颜色转换回十六进制:

Color newCol = Color.red;string htmlValue = ColorUtility.ToHtmlStringRGBA(newCol);

<小时><块引用>

所以没有办法只分配十六进制颜色而不检查它可以先转成RGB吗?

有.删除 if 语句.

ColorUtility.TryParseHtmlString(htmlValue, out newCol);btn.image.color = newCol;

不要这样做,因为您的 Color 结果可能是错误的.您应该使用 if 语句来处理这个问题,就像我在第一个代码中所做的那样.

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

解决方案

You are assigning bool to Color(btn.image.color).

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.

Below is what that code should look like:

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


So there is no way to just assign Hex color without checking that it can be converted to RGB first?

There is. Remove the if statement.

ColorUtility.TryParseHtmlString(htmlValue, out newCol);
btn.image.color = newCol;

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 将十六进制转换为颜色(RGBA)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆