'Flutter. Path scaling

How can I change the size of path in this section of code? When drawing, the path goes beyond the phone screen. I should not have access to drawing the paths themselves.

Path path = getPath();  //the path is given dynamically

canvas.drawPath(
  path,
  Paint()
    ..style = PaintingStyle.stroke
    ..color = Colors.black
    ..strokeWidth = 2.0);

I tried to use the method path.transform. But the path is not transformed correctly.



Solution 1:[1]

The code for adjustment is as follows.

main() => runApp(MaterialApp(home: SO()));

class SO extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        child: CustomPaint(
          painter: SOP(),
        ),
      ),
    );
  }
}

class SOP extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    Path p = getPath();

    Rect b = p.getBounds();
    var path_width = b.width;
    var path_height = b.height;
    var screen_width = size.width;
    var screen_height = size.height;
    var x_scale = screen_width / path_width;
    var y_scale = screen_height / path_height;

    //UNCOMMENT the following line to see the scaling effect
//    canvas.scale(x_scale, y_scale);

    canvas.drawPath(p, Paint()..color = Colors.red);
  }

  Path getPath() {
    Path p = Path();
    double w = 100;
    double h = 100;
    p.moveTo(0, 0);
    p.lineTo(0, h);
    p.lineTo(w, h);
    p.lineTo(w, 0);
    p.close();
    return p;
  }

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

Uncomment the scaling line to see the effect.

Solution 2:[2]

Doc proposed a solution by scaling the canvas. Another way would be to scale the path by using the transform method :

var scalingMatrix = Float64List.fromList(
    [size.width, 0, 0, 0,
    0, size.height, 0, 0,
    0, 0, 1, 0,
    0, 0, 0, 1]);
path = path.transform(scalingMatrix);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Tanguy