parseSvgSizeData function
Parses the area and offsets from an SVG <svg> element's attributes.
This function first attempts to extract and parse the viewBox attribute.
If viewBox is missing or malformed, it falls back to width and height
attributes. If neither is usable, returns null.
Returns a SvgSizeData instance on success, or null if parsing fails.
Implementation
SvgSizeData? parseSvgSizeData(XmlElement svg) {
final viewBox = svg.getAttribute('viewBox');
if (viewBox != null) {
final parts = viewBox.split(' ');
if (parts.length != 4) {
return null;
}
final minX = double.tryParse(parts[0]);
final minY = double.tryParse(parts[1]);
final width = double.tryParse(parts[2]);
final height = double.tryParse(parts[3]);
if (minX == null || minY == null || width == null || height == null) {
return null;
}
return SvgSizeData(
area: width * height,
widthOffset: -minX - width / 2,
heightOffset: -minY - height / 2,
);
} else {
final widthStr = svg.getAttribute('width');
final heightStr = svg.getAttribute('height');
if (widthStr == null || heightStr == null) {
return null;
}
final width = double.tryParse(widthStr);
final height = double.tryParse(widthStr);
if (width == null || height == null) {
return null;
}
return SvgSizeData(
area: width * height,
widthOffset: width / 2,
heightOffset: height / 2,
);
}
}