Home > Software design >  Flutter adding border to CustomPaint
Flutter adding border to CustomPaint

Time:03-18

I'm using CustomPainter to create a triangle. I want to create a triangle with a border.

My current result:
enter image description here

What I'm looking for:
enter image description here

My PaintTriangle class:

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

CodePudding user response:

You can draw another paint on canvas.

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

And use

 CustomPaint(
  size: Size(200, 200),
  painter: PaintTriangle(
    backgroundColor: Colors.blue,
    borderColor: Colors.red,
  ),
),

Result

image

CodePudding user response:

you will need to make another Custom Painter for the border with the same path as the triangle.

this link will answer your question

  • Related