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

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


当前回答

Color类需要一个ARGB整数。由于您尝试将它与RGB值一起使用,请将其表示为int并以0xff作为前缀。

Color mainColor = Color(0xffb74093);

如果您对此感到厌烦,并且仍然希望使用字符串,您可以扩展Color并添加一个字符串构造函数

class HexColor extends Color {
  static int _getColorFromHex(String hexColor) {
    hexColor = hexColor.toUpperCase().replaceAll("#", "");
    if (hexColor.length == 6) {
      hexColor = "FF" + hexColor;
    }
    return int.parse(hexColor, radix: 16);
  }

  HexColor(final String hexColor) : super(_getColorFromHex(hexColor));
}

使用

Color color1 = HexColor("b74093");
Color color2 = HexColor("#b74093");
Color color3 = HexColor("#88b74093"); // If you wish to use ARGB format

其他回答

“# 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;
}

这就是我的解决方案:

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

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

我使用这个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"));

如何在扑动中使用十六进制颜色代码#B74093

只需从十六进制颜色代码中删除#符号,并在color类中添加带有颜色代码的0xFF:

#b74093将在Flutter中变为Color(0xffb74093)

#B74093将在Flutter中变为Color(0xFFB74093)

ff或ff in Color(0xFFB74093)定义不透明度。

十六进制颜色的例子,所有不透明度类型在达特