svgToIcon function

MorphIconData svgToIcon(
  1. String source, {
  2. bool fit = true,
  3. double grid = 24,
})

An <svg> document → morphable icon data.

When fit is true (the default) and the document declares a coordinate space other than the target grid, the geometry is re-gridded onto it with fitIcon. That is what lets two SVGs drawn on different canvases — a 20×20 Heroicon and a 24×24 Lucide icon — morph into each other correctly instead of the alignment reading the grid difference as a zoom.

Implementation

MorphIconData svgToIcon(String source, {bool fit = true, double grid = 24}) {
  final doc = parseSvgDocument(source);
  if (doc.elements.isEmpty) {
    morphFail(
      'SVG has no supported geometry. This library morphs stroke outlines, so '
      'a document needs at least one of <path>, <line>, <circle>, <ellipse>, '
      '<rect>, <polyline> or <polygon> outside <defs>',
    );
  }
  final icon = NodeIcon(doc.elements);
  final vb = doc.viewBox;
  if (!fit || vb == null) return icon;
  final (minX, minY, w, h) = vb;
  // Already on the target grid: leave the element data alone, which keeps the
  // richer NodeIcon form instead of flattening everything to one path string.
  if (minX == 0 && minY == 0 && w == grid && h == grid) return icon;
  return PathIcon(fitIcon(icon, <num>[minX, minY, w, h], grid));
}