Flutter 为 CustomPaint 添加边框

gen*_*ser 3 flutter flutter-layout

我用来CustomPainter创建一个三角形。我想创建一个带边框的三角形。

我目前的结果:
在此输入图像描述

我正在寻找什么:
在此输入图像描述

我的 PaintTriangle 课程:

class PaintTriangle extends CustomPainter {
  final Color backgroundColor;

  PaintTriangle({
    required this.backgroundColor,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final y = size.height;
    final x = size.width;

    final paint = Paint()..color = backgroundColor;
    final path = Path()
      ..moveTo(0, y)
      ..lineTo((x / 2), (y / y))
      ..lineTo(x, y);

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}
Run Code Online (Sandbox Code Playgroud)

Md.*_*ikh 7

您可以在画布上绘制另一种颜料。

class PaintTriangle extends CustomPainter {
  final Color backgroundColor;
  final Color borderColor;

  final double borderThickness;

  PaintTriangle(
      {required this.backgroundColor,
      required this.borderColor,
      this.borderThickness = 4.0});

  @override
  void paint(Canvas canvas, Size size) {
    final y = size.height;
    final x = size.width;

    final paint = Paint()..color = backgroundColor;
    final path = Path()
      ..moveTo(0, y)
      ..lineTo((x / 2), (y / y))
      ..lineTo(x, y)
      ..lineTo(0, y); //little modification to draw bottom

    final borderPaint = Paint()
      ..color = borderColor
      ..style = PaintingStyle.stroke
      ..strokeWidth = borderThickness;
    canvas.drawPath(path, paint);
    canvas.drawPath(path, borderPaint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}
Run Code Online (Sandbox Code Playgroud)

并使用

 CustomPaint(
  size: Size(200, 200),
  painter: PaintTriangle(
    backgroundColor: Colors.blue,
    borderColor: Colors.red,
  ),
),
Run Code Online (Sandbox Code Playgroud)

结果

图像

  • 我从答案中得到的结论是笔划宽度。很好的答案。荣誉 (2认同)