flutter - 如何创建一个带有圆形边缘的自定义容器?

标签 flutter dart paint custom-painting

我正在尝试创建具有圆形边缘的自定义容器,但无法使拐角变为圆形。 current image
我只想使绿色容器的角变圆。

class MyPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    var paint = Paint()
      ..color = Colors.green.withOpacity(0.8)
      ..strokeWidth = 5
      ..strokeCap = StrokeCap.round;

    final shapeBounds = Rect.fromLTRB(0, 0, size.width, size.height);

    final path = Path()
      ..moveTo(shapeBounds.left + 10, shapeBounds.top) //3
      ..lineTo(shapeBounds.bottomLeft.dx + 10,shapeBounds.bottomLeft.dy) 
      ..lineTo(shapeBounds.bottomRight.dx,shapeBounds.bottomRight.dy - size.height * 0.12)
      ..lineTo(shapeBounds.topRight.dx - 20,
          shapeBounds.topRight.dy + size.height * 0.12) //7
      ..close();

    canvas.drawPath(path, paint);

  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return false;
  }
}

最佳答案

您可以使用 ClipPath 。在其中使用自定义Clipper 。在“自定义裁剪器”中,在绘制路径时使用 quadraticBezierTo。
enter image description here

class MyContainer extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ClipPath(
      clipper: MyClipper(),
      child: Container(
        child: Text("Dummy Text"),
        alignment: Alignment.center,
        color: Colors.green,
        width: 200,
        height: 200,
      ),
    );
  }
}

class MyClipper extends CustomClipper<Path> {
  Path getClip(Size size) {
    final path = Path();
    path
      ..lineTo(0.0, size.height * 0.1)
      ..quadraticBezierTo(0, 0, size.width * 0.1, 0)
      ..lineTo(size.width * 0.8, size.height * 0.12)
      ..quadraticBezierTo(size.width * 0.9, size.height * 0.15,
          size.width * 0.9, size.height * 0.2)
      ..lineTo(size.width, size.height * 0.9)
      ..quadraticBezierTo(
          size.width, size.height, size.width * 0.9, size.height)
      ..lineTo(size.width * 0.2, size.height * 0.9)
      ..quadraticBezierTo(size.width * 0.1, size.height * 0.9, size.width * 0.1,
          size.height * 0.8)
      ..close();
    return path;
  }

  @override
  bool shouldReclip(CustomClipper oldClipper) {
    return false;
  }
}

关于flutter - 如何创建一个带有圆形边缘的自定义容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63124913/

相关文章:

dart - 使用 F5 发送垃圾邮件时 Web 服务器崩溃

Dart:如何将 '0' json 解码为 double

java - 尝试使用 JFrame 和 JPanel 将窗口绘制为黑色

java - 在彼此之上的物体上绘画

Java swing.JFrame 仅在调整窗口大小时绘制内容

flutter - 在 ListView.builder 的末尾提供一些额外的空间

flutter - Riverpod,在 BuildContext 和 Provider 之外读取状态

flutter - 可重新排序列表中的弹出菜单不合适

flutter - 如何在 flutter 中返回用户流

flutter - 弹出式作用域小部件仅适用于我项目的最后一个屏幕,我想在每个页面或特定页面上使用它