我想在flutter中向用户进行ColorFiltered,这样我可以使jpg图像变暗这是我的代码,但我没有得到正确的结果,我不明白矩阵以及如何更改颜色此代码来自互联网,请知道将会受到欢迎。
ColorFiltered(
child: ColorFiltered(
child: Image.asset(
'myimage.jpg',
fit: BoxFit.fill,
),
colorFilter: ColorFilter.matrix(
[
//R G B A Const
-1, 0, 0, 0, 190, //
0, -1, 0, 0, 255, //
0, 0, -1, 0, 255, //
0, 0, 0, 1, 0, //
],
),
),
colorFilter: ColorFilter.mode(
Colors.white,
BlendMode.darken,
),
)
如果您只是想让图像变暗,更好的解决方案可能只是使用
Container
小部件在图像上放置透明的黑色 Stack
:
Stack(children: <Widget>[
Image.network('https://picsum.photos/250?image=9'),
Positioned.fill(
child: Opacity(
opacity: 0.5,
child: Container(
color: const Color(0xFF000000),
),
),
),
]),
如果你真的想使用
ColorFiltered
,请告诉我,但你可以这样做:
ColorFiltered(
child: Image.network('https://picsum.photos/250?image=9'),
colorFilter: const ColorFilter.mode(
Color(0xFF3D3D3D),
BlendMode.darken,
),
),
请记住,
ColorFiltered
不仅仅会在图像上添加新的灰色图层。它分别变换图像的每个像素。
根据文档:
此小部件根据指定的 ColorFilter 将函数独立应用于子内容的每个像素。
这是基于我的搜索和一些重构的结果:
static const List<double> identityMatrix = [
1,
0,
0,
0,
0,
0,
1,
0,
0,
0,
0,
0,
1,
0,
0,
0,
0,
0,
1,
0,
];
static ColorFilter brightnessAdjust(double value) {
if (value >= 0.0) {
value = value * 255;
} else {
value = value * 100;
}
List<double> matrix;
if (value == 0) {
matrix = identityMatrix;
} else {
matrix = [
1,
0,
0,
0,
value,
0,
1,
0,
0,
value,
0,
0,
1,
0,
value,
0,
0,
0,
1,
0
];
}
return ColorFilter.matrix(matrix);
}
正值变亮,负值变暗(-1到1),零不改变任何东西