Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I draw a custom box shadow in Flutter using Canvas in a CustomPaint?

Tags:

flutter

It's clear how to draw a shadow with an elevation property but what if I want to have the shadow centered for example?

like image 574
Jon Aird Avatar asked Mar 06 '19 23:03

Jon Aird


People also ask

How do you get a shadow box in Flutter?

BoxShadow is a built-in widget in flutter, whose functionality is to cast shadow to a box. The BoxShadow widget is usually used with BoxDecoration. In BoxDecoration widget one of its parameters is boxShadow which takes a list of BoxShadow to cast a shadow around a box.

How do you give shadow to one side of a container in Flutter?

new Container( decoration: BoxDecoration( color: Colors. grey. withOpacity(0.5), boxShadow: [ BoxShadow( blurRadius: 5.0 ), ], ), ), This code works but adds a shadow to every possible side of the container.


2 Answers

Found a solution:

I can simply go into the source code for the BoxShadow widget and apply the path properties they used to my own paths.

Here's the source code.

Here's the code that I used to create a shadow for a custom path (rather than a circle or rectangle with a border radius) that allowed me to create a custom shadow rather than using the elevation preset.

    canvas.drawPath(
       Path()
          ..addRect(
              Rect.fromPoints(Offset(-15, -15), Offset(size.width+15, size.height+15)))
          ..addOval(
              Rect.fromPoints(Offset(0, 0), Offset(size.width, size.height)))
          ..fillType = PathFillType.evenOdd,
        Paint() 
        ..color= Colors.black.withAlpha(shadowAlpha)
        ..maskFilter = MaskFilter.blur(BlurStyle.normal, convertRadiusToSigma(3))
    );

    static double convertRadiusToSigma(double radius) {
        return radius * 0.57735 + 0.5;
    }
like image 60
Jon Aird Avatar answered Oct 11 '22 06:10

Jon Aird


To draw shadow on CustomPaint you can use painter.

CustomPaint(
  painter: BoxShadowPainter(),
  child: ClipPath(
  clipper: MyClipper(), //my CustomClipper
  child: Container(), // my widgets inside
)));

check my answer here

like image 23
user969068 Avatar answered Oct 11 '22 05:10

user969068