我如何转换一个十六进制的颜色字符串像#b74093在扑动的颜色?
我想在Dart中使用HEX颜色代码。
我如何转换一个十六进制的颜色字符串像#b74093在扑动的颜色?
我想在Dart中使用HEX颜色代码。
当前回答
如果您想使用格式为#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"));
一个不使用类的简单函数:
Color _colorFromHex(String hexColor) {
final hexCode = hexColor.replaceAll('#', '');
return Color(int.parse('FF$hexCode', radix: 16));
}
你可以这样使用它:
Color color1 = _colorFromHex("b74093");
Color color2 = _colorFromHex("#b74093");
不需要使用函数。
例如,使用colorcode为容器赋予颜色:
Container
(
color:Color(0xff000000)
)
这里的0xff是格式后面跟着颜色代码
在文件中添加此函数
Color parseColor(String color) {
String hex = color.replaceAll("#", "");
if (hex.isEmpty) hex = "ffffff";
if (hex.length == 3) {
hex = '${hex.substring(0, 1)}${hex.substring(0, 1)}${hex.substring(1, 2)}${hex.substring(1, 2)}${hex.substring(2, 3)}${hex.substring(2, 3)}';
}
Color col = Color(int.parse(hex, radix: 16)).withOpacity(1.0);
return col;
}
然后像-一样使用它
Container(
color: parseColor("#b74093")
)
import 'package:flutter/material.dart';
class HexToColor extends Color{
static _hexToColor(String code) {
return int.parse(code.substring(1, 7), radix: 16) + 0xFF000000;
}
HexToColor(final String code) : super(_hexToColor(code));
}
导入新类并像这样使用它:
HexToColor('#F2A03D')