我如何转换一个十六进制的颜色字符串像#b74093在扑动的颜色?
我想在Dart中使用HEX颜色代码。
我如何转换一个十六进制的颜色字符串像#b74093在扑动的颜色?
我想在Dart中使用HEX颜色代码。
当前回答
感谢提问,简单的解决方法如下:
//颜色为十六进制字符串
colorToHexString(Color color) {
return '#FF${color.value.toRadixString(16).substring(2, 8)}';
}
//十六进制字符串到颜色
hexStringToColor(String hexColor) {
hexColor = hexColor.toUpperCase().replaceAll("#", "");
if (hexColor.length == 6) {
hexColor = "FF" + hexColor;
}
return Color(int.parse(hexColor, radix: 16));
}
//如何调用函数
String hexCode = colorToHexString(Colors.green);
Color bgColor = hexStringToColor(hexCode);
print("$hexCode = $bgColor");
享受代码并帮助他人:)
其他回答
一个不使用类的简单函数:
Color _colorFromHex(String hexColor) {
final hexCode = hexColor.replaceAll('#', '');
return Color(int.parse('FF$hexCode', radix: 16));
}
你可以这样使用它:
Color color1 = _colorFromHex("b74093");
Color color2 = _colorFromHex("#b74093");
还有另一种解决方案。如果您将颜色存储为普通的十六进制字符串,并且不想为其添加不透明度(前导“FF”):
将十六进制字符串转换为int 要将十六进制字符串转换为整数,请执行以下操作之一: var myInt = int。解析(hexString,基数:16); 或 var myInt = int.parse("0x$hexString"); 作为0x(或-0x)的前缀将使int。将默认值解析为基数16。 通过代码添加不透明度到你的颜色 Color = new Color(myInt).withOpacity(1.0);
“# b74093”?好吧……
到HEX配方
int getColorHexFromStr(String colorStr)
{
colorStr = "FF" + colorStr;
colorStr = colorStr.replaceAll("#", "");
int val = 0;
int len = colorStr.length;
for (int i = 0; i < len; i++) {
int hexDigit = colorStr.codeUnitAt(i);
if (hexDigit >= 48 && hexDigit <= 57) {
val += (hexDigit - 48) * (1 << (4 * (len - 1 - i)));
} else if (hexDigit >= 65 && hexDigit <= 70) {
// A..F
val += (hexDigit - 55) * (1 << (4 * (len - 1 - i)));
} else if (hexDigit >= 97 && hexDigit <= 102) {
// a..f
val += (hexDigit - 87) * (1 << (4 * (len - 1 - i)));
} else {
throw new FormatException("An error occurred when converting a color");
}
}
return val;
}
你可以点击Color Widget,它会告诉你更深入的信息,这些字母代表什么。
你也可以使用Color.fromARGB()方法来创建自定义颜色,这对我来说更容易。使用Flutter Doctor颜色选择器网站为您的Flutter应用程序选择任何颜色。
要将十六进制字符串转换为整数,请执行以下操作:
int hexToInt(String hex)
{
int val = 0;
int len = hex.length;
for (int i = 0; i < len; i++) {
int hexDigit = hex.codeUnitAt(i);
if (hexDigit >= 48 && hexDigit <= 57) {
val += (hexDigit - 48) * (1 << (4 * (len - 1 - i)));
} else if (hexDigit >= 65 && hexDigit <= 70) {
// A..F
val += (hexDigit - 55) * (1 << (4 * (len - 1 - i)));
} else if (hexDigit >= 97 && hexDigit <= 102) {
// a..f
val += (hexDigit - 87) * (1 << (4 * (len - 1 - i)));
} else {
throw new FormatException("Invalid hexadecimal value");
}
}
return val;
}
电话的例子:
Color color = new Color(hexToInt("FFB74093"));