skip to Main Content

I would like to be able to draw both SVG images and painted graphics (mostly lines between the SVG) on a Flutter Canvas. Currently, I am stuck at the step of being able to paint SVG on the Canvas.

I tried different approaches with flutter_svg. The most sensible one seems (to me) to be the following. But when I execute the code, the blue circle appears, but not the Svg image (which I already checked that it works with flutter_svg). It also seems that I have sometime some warnings regarding a null reference to a closure, when I hot reload the app.

class MyCanvas extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()..color = Color.fromARGB(255, 15, 9, 184);

    vg
        .loadPicture(const SvgAssetLoader("assets/Monogramme_dark.svg"), null)
        .then((picture) => picture.picture
            .toImage(50, 50)
            .then((image) => canvas.drawImage(image, Offset(100, 100), paint)));

    canvas.drawCircle(Offset(50.0, 20.0), 10, paint);
  }

  @override
  bool shouldRepaint(MyCanvas oldDelegate) => false;
}

2

Answers


  1. There are different approaches.
    SVG is not an Image, but text like HTML/XML, that defines shapes, colors, size and form.

    This is an example of a Rectangle created with SVG from W3 Schools

    <svg width="400" height="110">
      <rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
    </svg>
    

    Knowing this, you can create methods to generate and iterate with your SVG elements and draw them on your application.

    You don’t need a canvas for this, you can literally use the default Flutter widgets to show how the SVG looks and generate an SVG image based on what you created.

    Login or Signup to reply.
  2. Try this code:

        class MyCanvas extends CustomPainter {
      @override
      void paint(Canvas canvas, Size size) {
        final paint = Paint()..color = Color.fromARGB(255, 15, 9, 184);
        final pictureInfo = await vg
            .loadPicture(const SvgAssetLoader("assets/Monogramme_dark.svg"), null);
        final image = await pictureInfo.picture.toImage(50, 50);
        canvas.drawImage(image, Offset(100, 100), paint);
        canvas.drawCircle(Offset(50.0, 20.0), 10, paint);
      }
      @override
      bool shouldRepaint(MyCanvas oldDelegate) => false;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search