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

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


当前回答

不需要使用函数。

例如,使用colorcode为容器赋予颜色:

Container
(
    color:Color(0xff000000)
)

这里的0xff是格式后面跟着颜色代码

其他回答

在fromRGB构造函数中使用十六进制数:

Color.fromRGBO(0xb7, 0x40, 0x93, 1),

文件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,
  )
)

在Flutter中,要从带alpha的RGB创建颜色,请使用:

return new Container(
  color: new Color.fromRGBO(0, 0, 0, 0.5),
);

如何使用十六进制颜色:

return new Container(
  color: new Color(0xFF4286f4),
);
// 0xFF -> the opacity (FF for opaque)
// 4286f4 -> the hexadecimal color

不透明的十六进制颜色:

return new Container(
  color: new Color(0xFF4286f4).withOpacity(0.5),
);

//或改变“FF”值

100% — FF
 95% — F2
 90% — E6
 85% — D9
 80% — CC
 75% — BF
 70% — B3
 65% — A6
 60% — 99
 55% — 8C
 50% — 80
 45% — 73
 40% — 66
 35% — 59
 30% — 4D
 25% — 40
 20% — 33
 15% — 26
 10% — 1A
 5% — 0D
 0% — 00

要了解更多信息,请参阅官方文档页,Color类- dart:ui库- dart API。

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

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

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

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

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

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

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