-
Notifications
You must be signed in to change notification settings - Fork 449
/
vector_drawable.dart
1282 lines (1108 loc) · 35.3 KB
/
vector_drawable.dart
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'dart:math' as math;
import 'dart:typed_data';
import 'dart:ui';
import 'package:meta/meta.dart';
import 'package:path_drawing/path_drawing.dart';
import 'package:vector_math/vector_math_64.dart';
import 'render_picture.dart' as render_picture;
import 'svg/parsers.dart' show affineMatrix;
import 'svg/xml_parsers.dart';
/// Paint used in masks.
final Paint _grayscaleDstInPaint = Paint()
..blendMode = BlendMode.dstIn
..colorFilter = const ColorFilter.matrix(<double>[
0, 0, 0, 0, 0, //
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0.2126, 0.7152, 0.0722, 0, 0,
]); //convert to grayscale (https://www.w3.org/Graphics/Color/sRGB) and use them as transparency
/// Base interface for vector drawing.
@immutable
abstract class Drawable {
/// Whether this [Drawable] would be visible if [draw]n.
bool get hasDrawableContent;
/// Draws the contents or children of this [Drawable] to the `canvas`, using
/// the `parentPaint` to optionally override the child's paint.
///
/// The `bounds` specify the area to draw in.
void draw(Canvas canvas, Rect bounds);
}
/// A [Drawable] that can have a [DrawableStyle] applied to it.
@immutable
abstract class DrawableStyleable extends Drawable {
/// The [DrawableStyle] for this object.
DrawableStyle get style;
/// The 4x4 transform to apply to this [Drawable], if any.
Float64List get transform;
/// Creates an instance with merged style information.
DrawableStyleable mergeStyle(DrawableStyle newStyle);
}
/// A [Drawable] that can have child [Drawables] and [DrawableStyle].
abstract class DrawableParent implements DrawableStyleable {
/// The child [Drawables] of this [DrawableParent].
///
/// Each child may itself have children.
List<Drawable> get children;
}
/// Styling information for vector drawing.
///
/// Contains [Paint], [Path], dashing, transform, and text styling information.
@immutable
class DrawableStyle {
/// Creates a new [DrawableStyle].
const DrawableStyle({
this.stroke,
this.dashArray,
this.dashOffset,
this.fill,
this.textStyle,
this.pathFillType,
this.groupOpacity,
this.clipPath,
this.mask,
this.blendMode,
});
/// Used where 'dasharray' is 'none'
///
/// This will not result in a drawing operation, but will clear out
/// inheritance.
static final CircularIntervalList<double> emptyDashArray =
CircularIntervalList<double>(const <double>[]);
/// If not `null` and not `identical` with [DrawablePaint.empty], will result in a stroke
/// for the rendered [DrawableShape]. Drawn __after__ the [fill].
final DrawablePaint stroke;
/// The dashing array to use for the [stroke], if any.
final CircularIntervalList<double> dashArray;
/// The [DashOffset] to use for where to begin the [dashArray].
final DashOffset dashOffset;
/// If not `null` and not `identical` with [DrawablePaint.empty], will result in a fill
/// for the rendered [DrawableShape]. Drawn __before__ the [stroke].
final DrawablePaint fill;
/// The style to apply to text elements of this drawable or its chidlren.
final DrawableTextStyle textStyle;
/// The fill rule to use for this path.
final PathFillType pathFillType;
/// The clip to apply, if any.
final List<Path> clipPath;
/// The mask to apply, if any.
final DrawableStyleable mask;
/// Controls group level opacity. Will be [BlendMode.dstIn] blended with any
/// children.
final double groupOpacity;
/// The blend mode to apply, if any.
///
/// Setting this will result in at least one [Canvas.saveLayer] call.
final BlendMode blendMode;
/// Creates a new [DrawableStyle] if `parent` is not null, filling in any null
/// properties on this with the properties from other (except [groupOpacity],
/// is not inherited).
static DrawableStyle mergeAndBlend(
DrawableStyle parent, {
DrawablePaint fill,
DrawablePaint stroke,
CircularIntervalList<double> dashArray,
DashOffset dashOffset,
DrawableTextStyle textStyle,
PathFillType pathFillType,
double groupOpacity,
List<Path> clipPath,
DrawableStyleable mask,
BlendMode blendMode,
}) {
return DrawableStyle(
fill: DrawablePaint.merge(fill, parent?.fill),
stroke: DrawablePaint.merge(stroke, parent?.stroke),
dashArray: dashArray ?? parent?.dashArray,
dashOffset: dashOffset ?? parent?.dashOffset,
textStyle: DrawableTextStyle.merge(textStyle, parent?.textStyle),
pathFillType: pathFillType ?? parent?.pathFillType,
groupOpacity: groupOpacity,
// clips don't make sense to inherit - applied to canvas with save/restore
// that wraps any potential children
clipPath: clipPath,
mask: mask,
blendMode: blendMode,
);
}
/// Averages [back] and [front]. If either is null, returns the other.
///
/// Result is null if both [back] and [front] are null.
static double mergeOpacity(double back, double front) {
if (back == null) {
return front;
} else if (front == null) {
return back;
}
return (front + back) / 2.0;
}
@override
String toString() {
return 'DrawableStyle{$stroke,$dashArray,$dashOffset,$fill,$textStyle,$pathFillType,$groupOpacity,$clipPath,$mask}';
}
}
/// A wrapper class for Flutter's [Paint] class.
///
/// Provides non-opaque access to painting properties.
@immutable
class DrawablePaint {
/// Creates a new [DrawablePaint] object.
const DrawablePaint(
this.style, {
this.color,
this.shader,
this.blendMode,
this.colorFilter,
this.isAntiAlias,
this.filterQuality,
this.maskFilter,
this.strokeCap,
this.strokeJoin,
this.strokeMiterLimit,
this.strokeWidth,
});
/// Will merge two DrawablePaints, preferring properties defined in `a` if they're not null.
///
/// If `a` is `identical` wiht [DrawablePaint.empty], `b` will be ignored.
factory DrawablePaint.merge(DrawablePaint a, DrawablePaint b) {
if (a == null && b == null) {
return null;
}
if (b == null && a != null) {
return a;
}
if (identical(a, DrawablePaint.empty) ||
identical(b, DrawablePaint.empty)) {
return a ?? b;
}
if (a == null) {
return b;
}
// If we got here, the styles should not be null.
assert(a.style == b.style,
'Cannot merge Paints with different PaintStyles; got:\na: $a\nb: $b.');
return DrawablePaint(
a.style ?? b.style,
color: a.color ?? b.color,
shader: a.shader ?? b.shader,
blendMode: a.blendMode ?? b.blendMode,
colorFilter: a.colorFilter ?? b.colorFilter,
isAntiAlias: a.isAntiAlias ?? b.isAntiAlias,
filterQuality: a.filterQuality ?? b.filterQuality,
maskFilter: a.maskFilter ?? b.maskFilter,
strokeCap: a.strokeCap ?? b.strokeCap,
strokeJoin: a.strokeJoin ?? b.strokeJoin,
strokeMiterLimit: a.strokeMiterLimit ?? b.strokeMiterLimit,
strokeWidth: a.strokeWidth ?? b.strokeWidth,
);
}
/// An empty [DrawablePaint].
///
/// Used to assist with inheritance of painting properties.
static const DrawablePaint empty = DrawablePaint(null);
/// Returns whether this paint is null or equivalent to SVG's "none".
static bool isEmpty(DrawablePaint paint) {
return paint == null || paint == empty;
}
/// The color to use for this paint when stroking or filling a shape.
final Color color;
/// The [Shader] to use when stroking or filling a shape.
final Shader shader;
/// The [BlendMode] to use when stroking or filling a shape.
final BlendMode blendMode;
/// A color filter to apply when a shape is drawn or layer is composited.
final ColorFilter colorFilter;
/// Whether to apply anti-aliasing to the lines and images drawn.
///
/// Defaults to true.
final bool isAntiAlias;
/// Controls the performance vs quality trade-off to use when applying
/// filters, such as [maskFilter], or when drawing images, as with
/// [Canvas.drawImageRect] or [Canvas.drawImageNine].
///
/// Defaults to [FilterQuality.none].
final FilterQuality filterQuality;
/// A mask filter (for example, a blur) to apply to a shape after it has been
/// drawn but before it has been composited into the image.
///
/// See [MaskFilter] for details.
final MaskFilter maskFilter;
/// Whehter to fill or stroke when drawing this shape.
final PaintingStyle style;
/// The [StrokeCap] for this shape.
final StrokeCap strokeCap;
/// The [StrokeJoin] for this shape.
final StrokeJoin strokeJoin;
/// The stroke miter limit. See [Paint.strokeMiterLimit].
final double strokeMiterLimit;
/// The width of strokes for this paint.
final double strokeWidth;
/// Creates a [Paint] object from this [DrawablePaint].
Paint toFlutterPaint() {
final Paint paint = Paint();
// Null chekcs are needed here because the setters assert.
if (blendMode != null) {
paint.blendMode = blendMode;
}
if (color != null) {
paint.color = color;
}
if (colorFilter != null) {
paint.colorFilter = colorFilter;
}
if (filterQuality != null) {
paint.filterQuality = filterQuality;
}
if (isAntiAlias != null) {
paint.isAntiAlias = isAntiAlias;
}
if (maskFilter != null) {
paint.maskFilter = maskFilter;
}
if (shader != null) {
paint.shader = shader;
}
if (strokeCap != null) {
paint.strokeCap = strokeCap;
}
if (strokeJoin != null) {
paint.strokeJoin = strokeJoin;
}
if (strokeMiterLimit != null) {
paint.strokeMiterLimit = strokeMiterLimit;
}
if (strokeWidth != null) {
paint.strokeWidth = strokeWidth;
}
if (style != null) {
paint.style = style;
}
return paint;
}
@override
String toString() {
return 'DrawablePaint{$style, color: $color, shader: $shader, blendMode: $blendMode, '
'colorFilter: $colorFilter, isAntiAlias: $isAntiAlias, filterQuality: $filterQuality, '
'maskFilter: $maskFilter, strokeCap: $strokeCap, strokeJoin: $strokeJoin, '
'strokeMiterLimit: $strokeMiterLimit, strokeWidth: $strokeWidth}';
}
}
/// A wrapper class for Flutter's [TextStyle] class.
///
/// Provides non-opaque access to text styling properties.
@immutable
class DrawableTextStyle {
/// Creates a new [DrawableTextStyle].
const DrawableTextStyle({
this.decoration,
this.decorationColor,
this.decorationStyle,
this.fontWeight,
this.fontFamily,
this.fontSize,
this.fontStyle,
this.foreground,
this.background,
this.letterSpacing,
this.wordSpacing,
this.height,
this.locale,
this.textBaseline,
this.anchor,
});
/// Merges two drawable text styles together, prefering set properties from [b].
factory DrawableTextStyle.merge(DrawableTextStyle a, DrawableTextStyle b) {
if (b == null) {
return a;
}
if (a == null) {
return b;
}
return DrawableTextStyle(
decoration: a.decoration ?? b.decoration,
decorationColor: a.decorationColor ?? b.decorationColor,
decorationStyle: a.decorationStyle ?? b.decorationStyle,
fontWeight: a.fontWeight ?? b.fontWeight,
fontStyle: a.fontStyle ?? b.fontStyle,
textBaseline: a.textBaseline ?? b.textBaseline,
fontFamily: a.fontFamily ?? b.fontFamily,
fontSize: a.fontSize ?? b.fontSize,
letterSpacing: a.letterSpacing ?? b.letterSpacing,
wordSpacing: a.wordSpacing ?? b.wordSpacing,
height: a.height ?? b.height,
locale: a.locale ?? b.locale,
background: a.background ?? b.background,
foreground: a.foreground ?? b.foreground,
anchor: a.anchor ?? b.anchor,
);
}
/// The [TextDecoration] to draw with this text.
final TextDecoration decoration;
/// The color to use when drawing the decoration.
final Color decorationColor;
/// The [TextDecorationStyle] of the decoration.
final TextDecorationStyle decorationStyle;
/// The weight of the font.
final FontWeight fontWeight;
/// The style of the font.
final FontStyle fontStyle;
/// The [TextBaseline] to use when drawing this text.
final TextBaseline textBaseline;
/// The font family to use when drawing this text.
final String fontFamily;
/// The font size to use when drawing this text.
final double fontSize;
/// The letter spacing to use when drawing this text.
final double letterSpacing;
/// The word spacing to use when drawing this text.
final double wordSpacing;
/// The height of the text.
final double height;
/// The [Locale] to use when drawing this text.
final Locale locale;
/// The background to use when drawing this text.
final DrawablePaint background;
/// The foreground to use when drawing this text.
final DrawablePaint foreground;
/// The [DrawableTextAnchorPosition] to use when drawing this text.
final DrawableTextAnchorPosition anchor;
/// Creates a Flutter [TextStyle], overriding the foreground if specified.
TextStyle toFlutterTextStyle({DrawablePaint foregroundOverride}) {
return TextStyle(
decoration: decoration,
decorationColor: decorationColor,
decorationStyle: decorationStyle,
fontWeight: fontWeight,
fontStyle: fontStyle,
textBaseline: textBaseline,
fontFamily: fontFamily,
fontSize: fontSize,
letterSpacing: letterSpacing,
wordSpacing: wordSpacing,
height: height,
locale: locale,
background: background?.toFlutterPaint(),
foreground:
foregroundOverride?.toFlutterPaint() ?? foreground?.toFlutterPaint(),
);
}
@override
String toString() =>
'DrawableTextStyle{$decoration,$decorationColor,$decorationStyle,$fontWeight,'
'$fontFamily,$fontSize,$fontStyle,$foreground,$background,$letterSpacing,$wordSpacing,$height,'
'$locale,$textBaseline,$anchor}';
}
/// How to anchor text.
enum DrawableTextAnchorPosition {
/// The offset specifies the start of the text.
start,
/// The offset specifies the midpoint of the text.
middle,
/// The offset specifies the end of the text.
end,
}
/// A [Drawable] for text objects.
class DrawableText implements Drawable {
/// Creates a new [DrawableText] object.
///
/// One of fill or stroke must be specified.
DrawableText(
this.fill,
this.stroke,
this.offset,
this.anchor, {
this.transform,
}) : assert(fill != null || stroke != null);
/// The offset for positioning the text. The [anchor] property controls
/// how this offset is interpreted.
final Offset offset;
/// The anchor for the offset, i.e. whether it is the start, middle, or end
/// of the text.
final DrawableTextAnchorPosition anchor;
/// If specified, how to draw the interior portion of the text.
final Paragraph fill;
/// If specified, how to draw the outline of the text.
final Paragraph stroke;
/// A transform to apply when drawing the text.
final Float64List transform;
@override
bool get hasDrawableContent =>
(fill?.width ?? 0.0) + (stroke?.width ?? 0.0) > 0.0;
@override
void draw(Canvas canvas, Rect bounds) {
if (!hasDrawableContent) {
return;
}
if (transform != null) {
canvas.save();
canvas.transform(transform);
}
if (fill != null) {
canvas.drawParagraph(fill, resolveOffset(fill, anchor, offset));
}
if (stroke != null) {
canvas.drawParagraph(stroke, resolveOffset(stroke, anchor, offset));
}
if (transform != null) {
canvas.restore();
}
}
/// Determines the correct location for an [Offset] given laid-out
/// [paragraph] and a [DrawableTextPosition].
static Offset resolveOffset(
Paragraph paragraph,
DrawableTextAnchorPosition anchor,
Offset offset,
) {
assert(paragraph != null);
assert(anchor != null);
assert(offset != null);
switch (anchor) {
case DrawableTextAnchorPosition.middle:
return Offset(
offset.dx - paragraph.minIntrinsicWidth / 2,
offset.dy - paragraph.alphabeticBaseline,
);
break;
case DrawableTextAnchorPosition.end:
return Offset(
offset.dx - paragraph.minIntrinsicWidth,
offset.dy - paragraph.alphabeticBaseline,
);
break;
case DrawableTextAnchorPosition.start:
return Offset(
offset.dx,
offset.dy - paragraph.alphabeticBaseline,
);
break;
default:
return offset;
break;
}
}
}
/// Contains reusable drawing elements that can be referenced by a String ID.
class DrawableDefinitionServer {
final Map<String, DrawableGradient> _gradients = <String, DrawableGradient>{};
final Map<String, List<Path>> _clipPaths = <String, List<Path>>{};
final Map<String, DrawableStyleable> _drawables =
<String, DrawableStyleable>{};
/// Attempt to lookup a [Drawable] by [id].
DrawableStyleable getDrawable(String id, {bool nullOk = false}) {
assert(id != null);
final DrawableStyleable value = _drawables[id];
if (value == null && nullOk != true) {
throw StateError('Expected to find Drawable with id $id.\n'
'Have ids: ${_drawables.keys}');
}
return value;
}
/// Add a [Drawable] that can later be referred to by [id].
void addDrawable(String id, DrawableStyleable drawable) {
assert(id != null);
assert(drawable != null);
assert(id != emptyUrlIri);
_drawables[id] = drawable;
}
/// Attempt to lookup a pre-defined [Shader] by [id].
///
/// [id] and [bounds] must not be null.
Shader getShader(String id, Rect bounds) {
assert(id != null);
assert(bounds != null);
final DrawableGradient srv = _gradients[id];
return srv != null ? srv.createShader(bounds) : null;
}
/// Retreive a gradient from the pre-defined [DrawableGradient] collection.
T getGradient<T extends DrawableGradient>(String id) {
assert(id != null);
return _gradients[id] as T;
}
/// Add a [DrawableGradient] to the pre-defined collection by [id].
void addGradient(String id, DrawableGradient gradient) {
assert(id != null);
assert(gradient != null);
_gradients[id] = gradient;
}
/// Get a [List<Path>] of clip paths by [id].
List<Path> getClipPath(String id) {
assert(id != null);
return _clipPaths[id];
}
/// Add a [List<Path>] of clip paths by [id].
void addClipPath(String id, List<Path> paths) {
assert(id != null);
assert(paths != null);
_clipPaths[id] = paths;
}
}
/// Determines how to transform the points given for a gradient.
enum GradientUnitMode {
/// The gradient vector(s) are transformed by the space in the object containing the gradient.
objectBoundingBox,
/// The gradient vector(s) are taken as is.
userSpaceOnUse,
}
/// Basic information describing a gradient.
@immutable
abstract class DrawableGradient {
/// Initializes basic values.
const DrawableGradient(
this.offsets,
this.colors, {
this.spreadMethod = TileMode.clamp,
this.unitMode = GradientUnitMode.objectBoundingBox,
this.transform,
});
/// Specifies where `colors[i]` begins in the gradient.
///
/// Number of elements must equal the number of elements in [colors].
final List<double> offsets;
/// The colors to use for the gradient.
final List<Color> colors;
/// The [TileMode] to use for this gradient.
final TileMode spreadMethod;
/// The [GradientUnitMode] for any vectors specified by this gradient.
final GradientUnitMode unitMode;
/// The transform to apply to this gradient.
final Float64List transform;
/// Creates a [Shader] (i.e. a [Gradient]) from this object.
Shader createShader(Rect bounds);
}
/// Represents the data needed to create a [Gradient.linear].
@immutable
class DrawableLinearGradient extends DrawableGradient {
/// Creates a new [DrawableLinearGradient].
const DrawableLinearGradient({
@required this.from,
@required this.to,
@required List<double> offsets,
@required List<Color> colors,
@required TileMode spreadMethod,
@required GradientUnitMode unitMode,
Float64List transform,
}) : super(
offsets,
colors,
spreadMethod: spreadMethod,
unitMode: unitMode,
transform: transform,
);
/// The starting offset of this gradient.
final Offset from;
/// The ending offset of this gradient.
final Offset to;
@override
Shader createShader(Rect bounds) {
final bool isObjectBoundingBox =
unitMode == GradientUnitMode.objectBoundingBox;
Matrix4 m4transform = transform == null
? Matrix4.identity()
: Matrix4.fromFloat64List(transform);
if (isObjectBoundingBox) {
final Matrix4 scale =
affineMatrix(bounds.width, 0.0, 0.0, bounds.height, 0.0, 0.0);
final Matrix4 translate =
affineMatrix(1.0, 0.0, 0.0, 1.0, bounds.left, bounds.top);
m4transform = translate.multiplied(scale)..multiply(m4transform);
}
final Vector3 v3from = m4transform.transform3(
Vector3(
from.dx,
from.dy,
0.0,
),
);
final Vector3 v3to = m4transform.transform3(
Vector3(
to.dx,
to.dy,
0.0,
),
);
return Gradient.linear(
Offset(v3from.x, v3from.y),
Offset(v3to.x, v3to.y),
colors,
offsets,
spreadMethod,
);
}
}
/// Represents the information needed to create a [Gradient.radial].
@immutable
class DrawableRadialGradient extends DrawableGradient {
/// Creates a [DrawableRadialGradient].
const DrawableRadialGradient({
@required this.center,
@required this.radius,
@required this.focal,
this.focalRadius = 0.0,
@required List<double> offsets,
@required List<Color> colors,
@required TileMode spreadMethod,
@required GradientUnitMode unitMode,
Float64List transform,
}) : super(
offsets,
colors,
spreadMethod: spreadMethod,
unitMode: unitMode,
transform: transform,
);
/// The center of the radial gradient.
final Offset center;
/// The radius of the radial gradient.
final double radius;
/// The focal point, if any, for a two point conical gradient.
final Offset focal;
/// The radius of the focal point.
final double focalRadius;
@override
Shader createShader(Rect bounds) {
final bool isObjectBoundingBox =
unitMode == GradientUnitMode.objectBoundingBox;
Matrix4 m4transform = transform == null
? Matrix4.identity()
: Matrix4.fromFloat64List(transform);
if (isObjectBoundingBox) {
final Matrix4 scale =
affineMatrix(bounds.width, 0.0, 0.0, bounds.height, 0.0, 0.0);
final Matrix4 translate =
affineMatrix(1.0, 0.0, 0.0, 1.0, bounds.left, bounds.top);
m4transform = translate.multiplied(scale)..multiply(m4transform);
}
return Gradient.radial(
center,
radius,
colors,
offsets,
spreadMethod,
m4transform.storage,
focal,
0.0,
);
}
}
/// Contains the viewport size and offset for a Drawable.
@immutable
class DrawableViewport {
/// Creates a new DrawableViewport, which acts as a bounding box for the Drawable
/// and specifies what offset (if any) the coordinate system needs to be translated by.
///
/// Both `rect` and `offset` must not be null.
const DrawableViewport(
this.size,
this.viewBox, {
this.viewBoxOffset = Offset.zero,
}) : assert(size != null),
assert(viewBox != null),
assert(viewBoxOffset != null);
/// The offset for all drawing commands in this Drawable.
final Offset viewBoxOffset;
/// A [Rect] representing the viewBox of this DrawableViewport.
Rect get viewBoxRect => Offset.zero & viewBox;
/// The viewBox size for the drawable.
final Size viewBox;
/// The viewport size of the drawable.
///
/// This may or may not be identical to the
final Size size;
/// The width of the viewport rect.
double get width => size.width;
/// The height of the viewport rect.
double get height => size.height;
@override
String toString() => 'DrawableViewport{$size, viewBox: $viewBox, '
'viewBoxOffset: $viewBoxOffset}';
}
/// The root element of a drawable.
class DrawableRoot implements DrawableParent {
/// Creates a new [DrawableRoot].
const DrawableRoot(
this.viewport,
this.children,
this.definitions,
this.style, {
this.transform,
});
/// The expected coordinates used by child paths for drawing.
final DrawableViewport viewport;
@override
final Float64List transform;
@override
final List<Drawable> children;
/// Contains reusable definitions such as gradients and clipPaths.
final DrawableDefinitionServer definitions;
/// The [DrawableStyle] for inheritence.
@override
final DrawableStyle style;
/// Scales the `canvas` so that the drawing units in this [Drawable]
/// will scale to the `desiredSize`.
///
/// If the `viewBox` dimensions are not 1:1 with `desiredSize`, will scale to
/// the smaller dimension and translate to center the image along the larger
/// dimension.
void scaleCanvasToViewBox(Canvas canvas, Size desiredSize) {
render_picture.scaleCanvasToViewBox(
canvas,
desiredSize,
viewport.viewBoxRect,
viewport.size,
);
}
/// Clips the canvas to a rect corresponding to the `viewBox`.
void clipCanvasToViewBox(Canvas canvas) {
canvas.clipRect(viewport.viewBoxRect);
}
@override
bool get hasDrawableContent =>
children.isNotEmpty == true &&
viewport != null &&
!viewport.viewBox.isEmpty;
@override
void draw(Canvas canvas, Rect bounds) {
if (!hasDrawableContent) {
return;
}
if (transform != null) {
canvas.save();
canvas.transform(transform);
}
if (viewport.viewBoxOffset != Offset.zero) {
canvas.translate(viewport.viewBoxOffset.dx, viewport.viewBoxOffset.dy);
}
for (Drawable child in children) {
child.draw(canvas, viewport.viewBoxRect);
}
if (transform != null) {
canvas.restore();
}
if (viewport.viewBoxOffset != Offset.zero) {
canvas.restore();
}
}
/// Creates a [Picture] from this [DrawableRoot].
///
/// Be cautious about not clipping to the ViewBox - you will be
/// allowing your drawing to take more memory than it otherwise would,
/// particularly when it is eventually rasterized.
Picture toPicture({
Size size,
bool clipToViewBox = true,
ColorFilter colorFilter,
}) {
if (viewport == null || viewport.viewBox.width == 0) {
return null;
}
final PictureRecorder recorder = PictureRecorder();
final Canvas canvas = Canvas(recorder, viewport.viewBoxRect);
if (colorFilter != null) {
canvas.saveLayer(null, Paint()..colorFilter = colorFilter);
} else {
canvas.save();
}
if (size != null) {
scaleCanvasToViewBox(canvas, size);
}
if (clipToViewBox == true) {
clipCanvasToViewBox(canvas);
}
draw(canvas, viewport.viewBoxRect);
canvas.restore();
return recorder.endRecording();
}
@override
DrawableRoot mergeStyle(DrawableStyle newStyle) {
assert(newStyle != null);
final DrawableStyle mergedStyle = DrawableStyle.mergeAndBlend(
style,
fill: newStyle.fill,
stroke: newStyle.stroke,
clipPath: newStyle.clipPath,
mask: newStyle.mask,
dashArray: newStyle.dashArray,
dashOffset: newStyle.dashOffset,
pathFillType: newStyle.pathFillType,
textStyle: newStyle.textStyle,
);
return DrawableRoot(
viewport,
children,
definitions,
mergedStyle,
transform: transform,
);
}
}
/// Represents a group of drawing elements that may share a common `transform`,
/// `stroke`, or `fill`.
class DrawableGroup implements DrawableStyleable, DrawableParent {
/// Creates a new DrawableGroup.
const DrawableGroup(this.children, this.style, {this.transform});
@override
final List<Drawable> children;
@override
final DrawableStyle style;
@override
final Float64List transform;
@override
bool get hasDrawableContent => children != null && children.isNotEmpty;
@override
void draw(Canvas canvas, Rect bounds) {
if (!hasDrawableContent) {
return;
}
final Function innerDraw = () {