svg_string.dart
1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import 'package:flutter/widgets.dart';
import 'package:flutter_svg/flutter_svg.dart';
String svgStringFromPath(
String path,
Size viewPort,
Rect viewBox,
Color color, {
String preserveAspectRatio = 'xMidYMid meet',
}) =>
'<svg xmlns="http://www.w3.org/2000/svg" '
'width="${viewPort.width}" height="${viewPort.height}" '
'preserveAspectRatio="$preserveAspectRatio" '
'viewBox='
'"${viewBox.left} ${viewBox.top} ${viewBox.width} ${viewBox.height}" '
'>'
'<path fill="rgb(${color.red},${color.green},${color.blue})" d="$path"></path>'
'</svg>';
final _alignmentToString = {
Alignment.topLeft: 'xMinYMin',
Alignment.topCenter: 'xMidYMin',
Alignment.topRight: 'xMaxYMin',
Alignment.centerLeft: 'xMinYMid',
Alignment.center: 'xMidYMid',
Alignment.centerRight: 'xMaxYMid',
Alignment.bottomLeft: 'xMinYMax',
Alignment.bottomCenter: 'xMidYMax',
Alignment.bottomRight: 'xMaxYMax',
};
Widget svgWidgetFromPath(
String path,
Size viewPort,
Rect viewBox,
Color color, {
Alignment align = Alignment.topLeft,
BoxFit fit = BoxFit.fill,
}) {
final alignment = _alignmentToString[align];
assert(fit != BoxFit.none &&
fit != BoxFit.fitHeight &&
fit != BoxFit.fitWidth &&
fit != BoxFit.scaleDown);
final meetOrSlice = fit == BoxFit.contain ? 'meet' : 'slice';
final preserveAspectRatio =
fit == BoxFit.fill ? 'none' : '$alignment $meetOrSlice';
final svgString = svgStringFromPath(path, viewPort, viewBox, color,
preserveAspectRatio: preserveAspectRatio);
return Container(
height: viewPort.height,
width: viewPort.width,
child: SvgPicture.string(
svgString,
width: viewPort.width,
height: viewPort.height,
fit: fit,
alignment: align,
),
);
}