Search code examples
flutterdartshader

Overlay a gradient shader mask on part of the image


I'm using the following code to create a shadermask,

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

The effect that I'm trying to achieve is as follows,

enter image description here

Unfortunately, the above code overlays the gradient all over the image. How do I get the desired effect using shader mask? How can I sort this out?


Solution

  • You need to adjust your LinearGradient better.

    I change the ending color to Colors.transparent.

    But also provide the begin and end point for the gradient

    Try this code.

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

    Play with the colors and the stops params to adjust the effect.

    You can also change tileMode. Try TileMode.mirror or TileMode.clamp


    To add a border radius to the image wrap your Image() widget like this, with a ClipRRect()

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