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

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


当前回答

最简单的方法是将其转换为整数。例如,#BCE6EB。你会添加0xFF,然后你会删除标签,使它:

0 xffbce6eb

然后让我们假设你要通过这样做来实现它:

写成backgroundColor:颜色(0 xffbce6eb)

如果你只能使用十六进制,那么我建议使用Hexcolor包。

其他回答

你可以写一个小的控制台工具来转换字符串:

import 'dart:convert';
import 'dart:io';

void main() {
  while (true) {
    var line = stdin.readLineSync(encoding: utf8);

    print(HexColor.fromHex(line!));
  }
}

class HexColor {
  static fromHex(String hexString) {
    final buffer = StringBuffer();
    if (hexString.length == 6 || hexString.length == 7) buffer.write('ff');
    buffer.write(hexString.replaceFirst('#', ''));
    return int.parse(buffer.toString(), radix: 16);
  }
}

如果您想使用格式为#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

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

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

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

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