首页 > 解决方案 > 在部分图像上叠加渐变着色器遮罩

问题描述

我正在使用以下代码来创建着色器掩码,

  ShaderMask _gradientPng() {
    return ShaderMask(
      child: Image(
        image: AssetImage('images/profile2.jpg'),
        height: 150,
        width: 100,
        fit: BoxFit.fill,
      ),
      shaderCallback: (Rect bounds) {
        return LinearGradient(
          colors: [Color(0xFF396AEA), Color(0xFF3B6EEC)],
          stops: [
            0.0,
            0.5,
          ],
        ).createShader(bounds);
      },
      blendMode: BlendMode.overlay,
    );
  }

我想要达到的效果如下,

在此处输入图像描述

不幸的是,上面的代码覆盖了整个图像的渐变。如何使用着色器蒙版获得所需的效果?我该如何解决这个问题?

标签: flutterdartshader

解决方案


你需要LinearGradient更好地调整自己。

我将结束颜色更改为Colors.transparent

但也提供渐变的起点终点

试试这个代码。

LinearGradient(
  begin: Alignment.bottomCenter,
  end: Alignment.topCenter,
  colors: [Color(0xFF396AEA), Colors.transparent],
  stops: [
    0.0,
    0.7,
  ],
  tileMode: TileMode.mirror,
).createShader(bounds);

使用颜色停止参数来调整效果。

您还可以更改tileMode。尝试TileMode.mirrorTileMode.clamp


要为图像添加边框半径,Image()像这样包装您的小部件,使用ClipRRect()

 ClipRRect(
    borderRadius: BorderRadius.circular(20),
    child: Image(
      image: AssetImage('images/profile2.jpg'),
      fit: BoxFit.fill,
    ),
  )

推荐阅读