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

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


当前回答

不需要使用函数。

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

Container
(
    color:Color(0xff000000)
)

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

其他回答

不需要使用函数。

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

Container
(
    color:Color(0xff000000)
)

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

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

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

最好的方法是使用来自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)),
    ),

这里的特殊插件。

在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。

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

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