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

前端 未结 2 702
迷失自我
迷失自我 2021-02-08 06:46

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

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-08 07:43

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

提交回复
热议问题