在部分图像上叠加渐变着色器遮罩

Overlay a gradient shader mask on part of the image

我正在使用以下代码创建着色器遮罩,

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

我想实现的效果如下,

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

你需要更好地调整你的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);

使用 colorsstops 参数来调整效果。

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


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

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