我如何转换一个十六进制的颜色字符串像#b74093在扑动的颜色?
我想在Dart中使用HEX颜色代码。
我如何转换一个十六进制的颜色字符串像#b74093在扑动的颜色?
我想在Dart中使用HEX颜色代码。
当前回答
要将十六进制字符串转换为整数,请执行以下操作:
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"));
其他回答
文件utils.dart
///
/// Convert a color hex-string to a Color object.
///
Color getColorFromHex(String hexColor) {
hexColor = hexColor.toUpperCase().replaceAll('#', '');
if (hexColor.length == 6) {
hexColor = 'FF' + hexColor;
}
return Color(int.parse(hexColor, radix: 16));
}
示例使用
Text(
'Hello, World!',
style: TextStyle(
color: getColorFromHex('#aabbcc'),
fontWeight: FontWeight.bold,
)
)
这就是我的解决方案:
String hexString = "45a3df";
Color(int.parse("0xff${hexString}"));
这是唯一不需要额外步骤的方法。
你可以点击Color Widget,它会告诉你更深入的信息,这些字母代表什么。
你也可以使用Color.fromARGB()方法来创建自定义颜色,这对我来说更容易。使用Flutter Doctor颜色选择器网站为您的Flutter应用程序选择任何颜色。
在fromRGB构造函数中使用十六进制数:
Color.fromRGBO(0xb7, 0x40, 0x93, 1),
最好的方法是使用来自pub.dev的flutter十六进制颜色插件 然后导入包。
import 'package:hexcolor/hexcolor.dart';
然后把它用在这种特殊的方式上。
Text(
'Running on: $_platformVersion\n',
style: TextStyle(color: HexColor("#f2f2f2")),
),
Text(
"Hex From Material $textColor",
style: TextStyle(color: ColorToHex(Colors.teal)),
),
这里的特殊插件。