dnfield / flutter_svg

SVG parsing, rendering, and widget library for Flutter
MIT License
1.67k stars 458 forks source link

Migration to 2.x.x #963

Open dr953 opened 1 year ago

dr953 commented 1 year ago

Could you please share a snippet to help me migrate some v1 features? I have a hard time finding the info in the reference.

  1. First, getting some children:
DrawableRoot svgRoot = await svg.fromSvgString(svgString, 'svg');

List<Drawable> filteredChildren = [];
for (int i = 0; i < svgRoot.children.length; i++) {
    if(child.id.toString().contains('pickMe')) {
        filteredChildren.add(svgRoot.children[i]);
    }
}

And then, creating a new DrawableRoot (PictureInfo) for the picked children:

DrawableRoot newSvgRoot = DrawableRoot(
        oldSvgRoot.id,
        oldSvgRoot.viewport,
        filteredChildren,
        oldSvgRoot.definitions,
        oldSvgRoot.style
    );
  }
  1. Scaling the svg.

Should

rootSvg.scaleCanvasToViewBox(canvas, width, height);

be replaced with scaling of the canvas itself, before:

canvas.drawPicture(pictureInfo.picture);

or is there a replacement function for the v1 scaleCanvasToViewBox

thinkingalaud commented 4 months ago

I know this is old, but I also had a similar experience with migrating and how to preserve scaling. I was also using scaleCanvasToViewBox previously:

DrawableRoot image;
image.scaleCanvasToViewBox(canvas, size);
image.draw(canvas, Rect.zero);

and ended up replacing that with

paintImage(
  canvas: canvas,
  rect: Rect.fromLTWH(0, 0, size.width, size.height),
  image: pictureInfo.picture.toImageSync(
    pictureInfo.size.width.toInt(),
    pictureInfo.size.height.toInt(),
  ),
);
atn832 commented 6 days ago

I'm also trying to understand what happened to DrawableRoot and how to do what I used to do with it. Here's what I found: the package parses svg and compiles it into "bytecode". Later you can decode that bytecode and extract the shapes from it.

final loader = SvgStringLoader(svgString);
final byteData = await loader.loadBytes(context);
final codec = VectorGraphicsCodec();
// listener should implement VectorGraphicsCodecListener.
codec.decode(byteData, listener);

You'll need to add a dependency to the https://pub.dev/packages/vector_graphics_codec package. Feel free to check out https://pub.dev/documentation/vector_graphics_codec/latest/vector_graphics_codec/VectorGraphicsCodec/decode.html and https://pub.dev/documentation/vector_graphics_codec/latest/vector_graphics_codec/VectorGraphicsCodecListener-class.html for more information.

You can read my still incomplete notes at https://www.wafrat.com/upgrading-to-flutter_svg-2-0-0/.