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

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


当前回答

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

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

其他回答

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

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

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

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

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

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

使用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")),
        ),
    ),
),

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

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