【问题标题】:How can I create a rectangle with a border shadow in Flutter?如何在 Flutter 中创建带有边框阴影的矩形?
【发布时间】:2020-03-26 05:39:54
【问题描述】:

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

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

问题是阴影被绘制为好像矩形已被填充,因此在矩形内绘制了一个实心阴影,如您在此屏幕截图中所见:

我也试过这个,但我得到了相同的结果。

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

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

【问题讨论】:

  • 自定义 ShapeBorder 应该可以实现 - 请参阅此处的示例代码:stackoverflow.com/a/57943257/2252830
  • @pskink 感谢您的回复。但我不认为它会解决我的问题。正如您在第二个代码 sn-p 中看到的那样,我尝试将 ShapeDecorationRoundedRectangleBorder 作为 ShapeBorder。问题出在阴影上。我编辑了帖子并附上了我的代码结果的屏幕截图。
  • @pskink 我明白了,谢谢!我会试试这个。

标签: flutter


【解决方案1】:

你可以使用CustomPaint来做到这一点

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

【讨论】:

    猜你喜欢
    • 2020-03-15
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    • 2023-01-31
    • 2016-09-13
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    相关资源
    最近更新 更多