我如何转换一个十六进制的颜色字符串像#b74093在扑动的颜色?
我想在Dart中使用HEX颜色代码。
我如何转换一个十六进制的颜色字符串像#b74093在扑动的颜色?
我想在Dart中使用HEX颜色代码。
当前回答
简单的方法:
String color = yourHexColor.replaceAll('#', '0xff');
用法:
Container(
color: Color(int.parse(color)),
)
其他回答
供一般参考。有一种更简单的方法,使用supercharge图书馆。虽然您可以对所有提到的解决方案使用扩展方法,但您可以找到实用的用户库工具包。
"#ff00ff".toColor(); // Painless hex to color
"red".toColor(); // Supports all web color names
容易,对吧?
增压
import 'package:flutter/material.dart';
class HexToColor extends Color{
static _hexToColor(String code) {
return int.parse(code.substring(1, 7), radix: 16) + 0xFF000000;
}
HexToColor(final String code) : super(_hexToColor(code));
}
导入新类并像这样使用它:
HexToColor('#F2A03D')
文件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,
)
)
要将十六进制字符串转换为整数,请执行以下操作:
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"));
最好的方法是使用来自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)),
),
这里的特殊插件。