我如何转换一个十六进制的颜色字符串像#b74093在扑动的颜色?

我想在Dart中使用HEX颜色代码。


当前回答

你可以点击Color Widget,它会告诉你更深入的信息,这些字母代表什么。

你也可以使用Color.fromARGB()方法来创建自定义颜色,这对我来说更容易。使用Flutter Doctor颜色选择器网站为您的Flutter应用程序选择任何颜色。

其他回答

“# 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(0x800F1D41)表示50%,80表示50%。

详情请点击这里

我使用这个material_color_gen包,它的工作就像一个魅力

material_color_gen: ^2.0.0

使用:

import 'package:material_color_gen/material_color_gen.dart';
primarySwatch: Color(0xFFFF0000).toMaterialColor()

这是一个HexColor的例子:#ff0000 使用0xFF更改#的结果是:0xFFFF0000

官方链接: https://pub.dev/packages/material_color_gen

要将十六进制字符串转换为整数,请执行以下操作:

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

这就是我的解决方案:

String hexString = "45a3df";
Color(int.parse("0xff${hexString}"));

这是唯一不需要额外步骤的方法。