parseViewBox method

DrawableViewport? parseViewBox({
  1. bool nullOk = false,
})

Parses an SVG @viewBox attribute (e.g. 0 0 100 100) to a Rect.

The nullOk parameter controls whether this function should throw if there is no viewBox or width/height parameters.

The respectWidthHeight parameter specifies whether width and height attributes on the root SVG element should be treated in accordance with the specification.

Implementation

DrawableViewport? parseViewBox({bool nullOk = false}) {
  final String viewBox = getAttribute(attributes, 'viewBox')!;
  final String rawWidth = getAttribute(attributes, 'width')!;
  final String rawHeight = getAttribute(attributes, 'height')!;

  if (viewBox == '' && rawWidth == '' && rawHeight == '') {
    if (nullOk) {
      return null;
    }
    throw StateError('SVG did not specify dimensions\n\n'
        'The SVG library looks for a `viewBox` or `width` and `height` attribute '
        'to determine the viewport boundary of the SVG.  Note that these attributes, '
        'as with all SVG attributes, are case sensitive.\n'
        'During processing, the following attributes were found:\n'
        '  $attributes');
  }

  final double width = _parseRawWidthHeight(rawWidth);

  final double height = _parseRawWidthHeight(rawHeight);

  if (viewBox == '') {
    return DrawableViewport(
      Size(width, height),
      Size(width, height),
    );
  }

  final List<String> parts = viewBox.split(RegExp(r'[ ,]+'));
  if (parts.length < 4) {
    throw StateError('viewBox element must be 4 elements long');
  }

  return DrawableViewport(
    Size(width, height),
    Size(
      parseDouble(parts[2])!,
      parseDouble(parts[3])!,
    ),
    viewBoxOffset: Offset(
      -parseDouble(parts[0])!,
      -parseDouble(parts[1])!,
    ),
  );
}