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

时间:2019-12-01 10:59:56

标签: flutter

我必须创建一个仅在边框上带有阴影的圆形边框, 像这样:

我试图创建一个没有背景色,圆角边框和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)),
),

问题在于阴影的绘制就像填充了矩形一样,因此在矩形内部绘制了纯阴影,如您在此屏幕快照中所见: enter image description here

我也尝试过,但是得到了相同的结果。

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

有没有一种简单的方法可以达到预期的效果?还是只有定制的画家才有可能?

1 个答案:

答案 0 :(得分:0)

您可以使用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;
}