David PHAM-VAN

Add a graphic context stack

@@ -16,6 +16,7 @@ @@ -16,6 +16,7 @@
16 16
17 library pdf; 17 library pdf;
18 18
  19 +import 'dart:collection';
19 import 'dart:convert'; 20 import 'dart:convert';
20 import 'dart:math' as math; 21 import 'dart:math' as math;
21 import 'dart:typed_data'; 22 import 'dart:typed_data';
@@ -18,14 +18,25 @@ part of pdf; @@ -18,14 +18,25 @@ part of pdf;
18 18
19 enum PdfLineCap { joinMiter, joinRound, joinBevel } 19 enum PdfLineCap { joinMiter, joinRound, joinBevel }
20 20
  21 +@immutable
  22 +class _PdfGraphicsContext {
  23 + const _PdfGraphicsContext({@required this.ctm}) : assert(ctm != null);
  24 + final Matrix4 ctm;
  25 +
  26 + _PdfGraphicsContext copy() => _PdfGraphicsContext(ctm: ctm.clone());
  27 +}
  28 +
21 class PdfGraphics { 29 class PdfGraphics {
22 - PdfGraphics(this.page, this.buf); 30 + PdfGraphics(this.page, this.buf) {
  31 + _context = _PdfGraphicsContext(ctm: Matrix4.identity());
  32 + }
23 33
24 /// Ellipse 4-spline magic number 34 /// Ellipse 4-spline magic number
25 static const double _m4 = 0.551784; 35 static const double _m4 = 0.551784;
26 36
27 - /// Graphic context number  
28 - int _context = 0; 37 + /// Graphic context
  38 + _PdfGraphicsContext _context;
  39 + final Queue<_PdfGraphicsContext> _contextQueue = Queue<_PdfGraphicsContext>();
29 40
30 final PdfPage page; 41 final PdfPage page;
31 42
@@ -61,17 +72,17 @@ class PdfGraphics { @@ -61,17 +72,17 @@ class PdfGraphics {
61 /// When using [PdfPage], you can create another fresh Graphics instance, 72 /// When using [PdfPage], you can create another fresh Graphics instance,
62 /// which will draw over this one. 73 /// which will draw over this one.
63 void restoreContext() { 74 void restoreContext() {
64 - if (_context > 0) { 75 + if (_contextQueue.isNotEmpty) {
65 // restore graphics context 76 // restore graphics context
66 buf.putString('Q\n'); 77 buf.putString('Q\n');
67 - _context--; 78 + _context = _contextQueue.removeLast();
68 } 79 }
69 } 80 }
70 81
71 void saveContext() { 82 void saveContext() {
72 // save graphics context 83 // save graphics context
73 buf.putString('q\n'); 84 buf.putString('q\n');
74 - _context++; 85 + _contextQueue.addLast(_context.copy());
75 } 86 }
76 87
77 /// Draws an image onto the page. 88 /// Draws an image onto the page.
@@ -227,6 +238,12 @@ class PdfGraphics { @@ -227,6 +238,12 @@ class PdfGraphics {
227 final Float64List s = t.storage; 238 final Float64List s = t.storage;
228 buf.putNumList(<double>[s[0], s[1], s[4], s[5], s[12], s[13]]); 239 buf.putNumList(<double>[s[0], s[1], s[4], s[5], s[12], s[13]]);
229 buf.putString(' cm\n'); 240 buf.putString(' cm\n');
  241 + _context.ctm.multiply(t);
  242 + }
  243 +
  244 + /// Get the transformation Matrix
  245 + Matrix4 getTransform() {
  246 + return _context.ctm.clone();
230 } 247 }
231 248
232 /// This adds a line segment to the current path 249 /// This adds a line segment to the current path