How to create drop shadows in Flutter Canvas

How to create drop shadows in Flutter Canvas

Recently one of my Twitter followers asked if I could help to create drop shadows in Flutter canvas. Here's how you can approach that problem.

Using the CustomPainter in Flutter gives you access to a canvas, which you can use to draw directly on to. And canvas has a lot of functions for you to easily create shapes and do all kinds of compositing.

Easiest way to do this is to use canvas.drawShadow function. That function looks like this:

void drawShadow(
Path path,
Color color,
double elevation,
bool transparentOccluder
)

Draws a shadow for a Path representing the given material elevation. The transparentOccluder argument should be true if the occluding object is not opaque. The arguments must not be null.

We can quickly try this out as shown below:

  @override
  void paint(Canvas canvas, Size size) {
    // centre of the screen
    final c = Offset(size.width / 2.0, size.height / 2.0);

    // path for a square
    final path = Path()
      ..moveTo(c.dx, c.dy)
      ..lineTo(c.dx + 100, c.dy)
      ..lineTo(c.dx + 100, c.dy + 100)
      ..lineTo(c.dx, c.dy + 100);
    path.close();

    // draw shadow
    canvas.drawShadow(path, Colors.red, 10, false);
  }

Which results in something like below:

Screenshot 2021-08-15 at 13.58.30.png

Now we can draw our shape on top of the shadow, by adding the following few lines at the end of the paint function.

    // draw path
    // desired paint fill
    final paint = Paint()
      ..color = Colors.red
      ..style = PaintingStyle.fill;

    canvas.drawPath(path, paint);

Which results in a shadow like shown below:

Screenshot 2021-08-15 at 14.03.20.png

Now this looks fine, but if you look closely, the shadow can be seen from all directions, although more prominent from the bottom.

We can get a cleaner look, but with some extra work. This requires a simple co-ord translation

    // shift coord system to the south west
    canvas.translate(-3, 3);
    // draw path
    canvas.drawPath(path, paint);

Which results in

Screenshot 2021-08-15 at 14.13.02.png

Experiment with the Elevation (10) and the displacement(-3,3) in the above code to get your desired shadow effect.

If you like more on Flutter canvas, my YouTube channel has some videos on the topic

Title Image Credit: Photo by Tom Barrett on Unsplash