我如何转换一个十六进制的颜色字符串像#b74093在扑动的颜色?
我想在Dart中使用HEX颜色代码。
我如何转换一个十六进制的颜色字符串像#b74093在扑动的颜色?
我想在Dart中使用HEX颜色代码。
当前回答
最简单的方法是将其转换为整数。例如,#BCE6EB。你会添加0xFF,然后你会删除标签,使它:
0 xffbce6eb
然后让我们假设你要通过这样做来实现它:
写成backgroundColor:颜色(0 xffbce6eb)
如果你只能使用十六进制,那么我建议使用Hexcolor包。
其他回答
如果您想使用格式为#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
不需要使用函数。
例如,使用colorcode为容器赋予颜色:
Container
(
color:Color(0xff000000)
)
这里的0xff是格式后面跟着颜色代码
在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。
感谢提问,简单的解决方法如下:
//颜色为十六进制字符串
colorToHexString(Color color) {
return '#FF${color.value.toRadixString(16).substring(2, 8)}';
}
//十六进制字符串到颜色
hexStringToColor(String hexColor) {
hexColor = hexColor.toUpperCase().replaceAll("#", "");
if (hexColor.length == 6) {
hexColor = "FF" + hexColor;
}
return Color(int.parse(hexColor, radix: 16));
}
//如何调用函数
String hexCode = colorToHexString(Colors.green);
Color bgColor = hexStringToColor(hexCode);
print("$hexCode = $bgColor");
享受代码并帮助他人:)
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')