flutterflutter-custompainter

how to draw the lines outside the axis in Flutter CustomPaint


I have a Container with a CustomPaint as the parent. In the CustomPaint I just draw a line on the half surrounding of the Container. The line is drawn with half of its width inside the Container and the other half outside the Container. I want to draw the line completely outside of the Container. How can I achieve this behavior? Thanks in advance.

Here's how it looks like now: enter image description here

Here's my code:

Center(
        child: CustomPaint(
          painter: SeatDecorator(),
          child: Container(
            width: 150,
            height: 150,
            color: Colors.blue.withOpacity(0.5),
          ),
        ),
      )

My CustomPainter:

class SeatDecorator extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
      ..color = Colors.blue
      ..strokeCap = StrokeCap.square
      ..style = PaintingStyle.stroke
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = 8;

    Path path = Path();
    path.moveTo(0, size.height / 2);
    path.lineTo(0, 0);
    path.lineTo(size.width, 0);
    path.lineTo(size.width, size.height / 2);
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}

Solution

  • The stroke center uses the last point to draw on canvas, you can count half of the strokeWidth while positioning lines.

    class SeatDecorator extends CustomPainter {
      SeatDecorator({this.strokeWidth = 8});
      final double strokeWidth;
      @override
      void paint(Canvas canvas, Size size) {
        Paint paint = Paint()
          ..color = Colors.blue
          ..strokeCap = StrokeCap.square
          ..style = PaintingStyle.stroke
          ..strokeJoin = StrokeJoin.round
          ..strokeWidth = strokeWidth;
    
        Path path = Path();
        final halfStrokeWidth = strokeWidth / 2;
        path.moveTo(-halfStrokeWidth, size.height / 2);
        path.lineTo(-halfStrokeWidth, -halfStrokeWidth);
        path.lineTo(size.width + halfStrokeWidth, -halfStrokeWidth);
        path.lineTo(size.width + halfStrokeWidth, size.height / 2);
        canvas.drawPath(path, paint);
      }
    
      @override
      bool shouldRepaint(covariant SeatDecorator oldDelegate) => oldDelegate.strokeWidth != strokeWidth;
    }
    

    You can use ShapeBorder for cases like this.