简体   繁体   English

如何在 Flutter 中创建带有边框阴影的矩形?

[英]How can I create a rectangle with a border shadow in Flutter?

I have to create a rounded border with a shadow only on the border, like this:我必须创建一个仅在边框上带有阴影的圆形边框,如下所示:

I have tried to create a container with no background color, a rounded border and a BoxShadow like this:我尝试创建一个没有背景颜色、圆形边框和 BoxShadow 的容器,如下所示:

Container(
  padding: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
  decoration: BoxDecoration(
    border: Border.all(color: Colors.white),
    borderRadius: BorderRadius.all(Radius.circular(5)),
    boxShadow: [
      const BoxShadow(
        color: Colors.black,
        blurRadius: 2,
        offset: Offset(0.0, 2.0),
      ),
    ],
  ),
  child: Text('text', style: TextStyle(color: Colors.white)),
),

The problem is that the shadow gets painted as if the rectangle was filled, so a solid shadow gets painted inside the rectangle, as you can see in this screenshot:问题是阴影被绘制为好像矩形被填充一样,所以在矩形内绘制了一个实心阴影,如您在此屏幕截图中所见: 在此处输入图片说明

I also tried this, but I got the same result.我也试过这个,但我得到了同样的结果。

Container(
  padding: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
  decoration: ShapeDecoration(
    shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.all(Radius.circular(3)),
      side: BorderSide(color: Colors.white),
    ),
    shadows: [
      const BoxShadow(
        color: Colors.black,
        blurRadius: 2,
        offset: Offset(0.0, 2.0),
      )
    ],
  ),
  child: Text('text', style: TextStyle(color: Colors.white)),
),

Is there a simple way I could achieve the desired effect?有没有一种简单的方法可以达到我想要的效果? Or it is only possible with a custom painter?或者只有定制画家才有可能?

You can do it using CustomPaint您可以使用CustomPaint

1

Container(
  child: CustomPaint(
    painter: MyPainter(),
    child: Container(
      padding: EdgeInsets.all(20),
      child: Text('text', style: TextStyle(color: Colors.white, fontSize: 30)),
    )
  ),
),
const double _kRadius = 10;
const double _kBorderWidth = 3;

class MyPainter extends CustomPainter {
  MyPainter();

  @override
  void paint(Canvas canvas, Size size) {
    final rrectBorder = RRect.fromRectAndRadius(Offset.zero & size, Radius.circular(_kRadius));
    final rrectShadow = RRect.fromRectAndRadius(Offset(0, 3) & size, Radius.circular(_kRadius));

    final shadowPaint = Paint()
      ..strokeWidth = _kBorderWidth
      ..color = Colors.black
      ..style = PaintingStyle.stroke
      ..maskFilter = MaskFilter.blur(BlurStyle.normal, 2);
    final borderPaint = Paint()
      ..strokeWidth = _kBorderWidth
      ..color = Colors.white
      ..style = PaintingStyle.stroke;

    canvas.drawRRect(rrectShadow, shadowPaint);
    canvas.drawRRect(rrectBorder, borderPaint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM