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

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


当前回答

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

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

其他回答

不需要使用函数。

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

Container
(
    color:Color(0xff000000)
)

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

如果您想使用格式为#123456的颜色的十六进制代码,那么很容易做到。创建一个类型为Color的变量,并将以下值赋给它。

Color myHexColor = Color(0xff123456)

// Here you notice I use the 0xff and that is the opacity or transparency
// of the color and you can also change these values.

使用myHexColor,你就可以开始了。

如果您想直接从十六进制代码更改颜色的不透明度,则将0xff中的ff值更改为下表中相应的值。(或者你也可以使用

myHexColor.withOpacity(0.2)

这是比较简单的方法。0.2是平均20%不透明度)

十六进制的不透明度值

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

还有另一种解决方案。如果您将颜色存储为普通的十六进制字符串,并且不想为其添加不透明度(前导“FF”):

将十六进制字符串转换为int 要将十六进制字符串转换为整数,请执行以下操作之一: var myInt = int。解析(hexString,基数:16); 或 var myInt = int.parse("0x$hexString"); 作为0x(或-0x)的前缀将使int。将默认值解析为基数16。 通过代码添加不透明度到你的颜色 Color = new Color(myInt).withOpacity(1.0);

使用hexcolor将十六进制颜色带入Dart hexcolorPlugin:

hexcolor: ^2.0.3

示例使用

import 'package:hexcolor/hexcolor.dart';
Container(
    decoration: new BoxDecoration(
        color: Hexcolor('#34cc89'),
    ),
    child: Center(
        child: Text(
            'Running on: $_platformVersion\n',
            style: TextStyle(color: Hexcolor("#f2f2f2")),
        ),
    ),
),

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