0

I want to draw lines in flutter with given List of points, everything works and the lines are drawn but the problem is, the drawing is not at the center of the canvas and is bigger then the canvas,

Here is my code snippet for the CustomPainter Class

class LinePainter extends CustomPainter {
  final List<Coordinate> coordinates;

  LinePainter({required this.coordinates});

  @override
  void paint(Canvas canvas, Size size) {
    final maxX =
        coordinates.map((c) => double.tryParse(c.x) ?? 0.0).reduce(max);
    final maxY =
        coordinates.map((c) => double.tryParse(c.y) ?? 0.0).reduce(max);
    final minX =
        coordinates.map((c) => double.tryParse(c.x) ?? 0.0).reduce(min);
    final minY =
        coordinates.map((c) => double.tryParse(c.y) ?? 0.0).reduce(min);

    final drawingWidth = maxX - minX;
    final drawingHeight = maxY - minY;

    final canvasWidth = size.width;
    final canvasHeight = size.height;

    double scaleFactor = 1.0;

    if (drawingWidth > canvasWidth || drawingHeight > canvasHeight) {
      scaleFactor =
          min(canvasWidth / drawingWidth, canvasHeight / drawingHeight);
    } else {
      scaleFactor =
          max(drawingWidth / canvasWidth, drawingHeight / canvasHeight);
    }

    final scaledWidth = drawingWidth * scaleFactor;
    final scaledHeight = drawingHeight * scaleFactor;

    final offsetX = ((canvasWidth - scaledWidth) / 2) - minX * scaleFactor;
    final offsetY = ((canvasHeight - scaledHeight) / 2) - minY * scaleFactor;

    final paint = Paint()
      ..color = Colors.black
      ..strokeWidth = 2.0;

    canvas.translate(offsetX, offsetY);
    canvas.scale(scaleFactor, scaleFactor);

    for (int i = 0; i < coordinates.length; i++) {
      final startX = double.parse(coordinates[i].x);
      final startY = double.parse(coordinates[i].y);
      final endX = double.parse(coordinates[(i + 1) % coordinates.length].x);
      final endY = double.parse(coordinates[(i + 1) % coordinates.length].y);

      final startPoint = Offset(startX, startY);
      final endPoint = Offset(endX, endY);

      canvas.drawLine(startPoint, endPoint, paint);
    }
  }

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

I have a fixed size canvas, 300 x 300, what I want is, if the drawing is bigger then the canvas, it should scale down and fit inside the canvas and centered it. or if the drawing is small then the canvas size, it should scale up and fit inside the canvas and centered it.

Here are the points I am providing to draw the lines, keep in mind, these points are changeable.

coordinates = [
      Coordinate(x: 10, y: 10),
      Coordinate(x: 20, y: 10),
      Coordinate(x: 30, y: 15),
      Coordinate(x: 25, y: 36),
      Coordinate(x: 10, y: 30),
      Coordinate(x: 5, y: 20),
    ];


CustomPaint(
   size: Size(400 , 300),
   painter: LinePainter(coordinates: coordinates),
        )

Any help is highly appreciated.

Ahmad
  • 95
  • 6

0 Answers0