-
Notifications
You must be signed in to change notification settings - Fork 136
/
screenshot.dart
400 lines (353 loc) · 11 KB
/
screenshot.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
library screenshot;
// import 'dart:io';
import 'dart:async';
import 'dart:typed_data';
// import 'package:path_provider/path_provider.dart';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'src/platform_specific/file_manager/file_manager.dart';
///
///
///Cannot capture Platformview due to issue https://github.com/flutter/flutter/issues/25306
///
///
class ScreenshotController {
late GlobalKey _containerKey;
ScreenshotController() {
_containerKey = GlobalKey();
}
/// Captures image and saves to given path
Future<String?> captureAndSave(
String directory, {
String? fileName,
double? pixelRatio,
Duration delay = const Duration(milliseconds: 20),
}) async {
Uint8List? content = await capture(
pixelRatio: pixelRatio,
delay: delay,
);
PlatformFileManager fileManager = PlatformFileManager();
return fileManager.saveFile(content!, directory, name: fileName);
}
Future<Uint8List?> capture({
double? pixelRatio,
Duration delay = const Duration(milliseconds: 20),
}) {
//Delay is required. See Issue https://github.com/flutter/flutter/issues/22308
return new Future.delayed(delay, () async {
ui.Image? image = await captureAsUiImage(
delay: Duration.zero,
pixelRatio: pixelRatio,
);
ByteData? byteData =
await image?.toByteData(format: ui.ImageByteFormat.png);
image?.dispose();
Uint8List? pngBytes = byteData?.buffer.asUint8List();
return pngBytes;
});
}
Future<ui.Image?> captureAsUiImage(
{double? pixelRatio = 1,
Duration delay = const Duration(milliseconds: 20)}) {
//Delay is required. See Issue https://github.com/flutter/flutter/issues/22308
return new Future.delayed(delay, () async {
try {
var findRenderObject =
this._containerKey.currentContext?.findRenderObject();
if (findRenderObject == null) {
return null;
}
RenderRepaintBoundary boundary =
findRenderObject as RenderRepaintBoundary;
BuildContext? context = _containerKey.currentContext;
if (pixelRatio == null) {
if (context != null)
pixelRatio = pixelRatio ?? MediaQuery.of(context).devicePixelRatio;
}
ui.Image image = await boundary.toImage(pixelRatio: pixelRatio ?? 1);
return image;
} catch (e) {
throw e;
}
});
}
///
/// Value for [delay] should increase with widget tree size. Prefered value is 1 seconds
///
///[context] parameter is used to Inherit App Theme and MediaQuery data.
///
///
///
Future<Uint8List> captureFromWidget(
Widget widget, {
Duration delay = const Duration(seconds: 1),
double? pixelRatio,
BuildContext? context,
Size? targetSize,
}) async {
ui.Image image = await widgetToUiImage(widget,
delay: delay,
pixelRatio: pixelRatio,
context: context,
targetSize: targetSize);
final ByteData? byteData =
await image.toByteData(format: ui.ImageByteFormat.png);
image.dispose();
return byteData!.buffer.asUint8List();
}
/// If you are building a desktop/web application that supports multiple view. Consider passing the [context] so that flutter know which view to capture.
static Future<ui.Image> widgetToUiImage(
Widget widget, {
Duration delay = const Duration(seconds: 1),
double? pixelRatio,
BuildContext? context,
Size? targetSize,
}) async {
///
///Retry counter
///
int retryCounter = 3;
bool isDirty = false;
Widget child = widget;
if (context != null) {
///
///Inherit Theme and MediaQuery of app
///
///
child = InheritedTheme.captureAll(
context,
MediaQuery(
data: MediaQuery.of(context),
child: Material(
child: child,
color: Colors.transparent,
)),
);
}
final RenderRepaintBoundary repaintBoundary = RenderRepaintBoundary();
final platformDispatcher = WidgetsBinding.instance.platformDispatcher;
final fallBackView = platformDispatcher.views.first;
final view =
context == null ? fallBackView : View.maybeOf(context) ?? fallBackView;
Size logicalSize =
targetSize ?? view.physicalSize / view.devicePixelRatio; // Adapted
Size imageSize = targetSize ?? view.physicalSize; // Adapted
assert(logicalSize.aspectRatio.toStringAsPrecision(5) ==
imageSize.aspectRatio
.toStringAsPrecision(5)); // Adapted (toPrecision was not available)
final RenderView renderView = RenderView(
view: view,
child: RenderPositionedBox(
alignment: Alignment.center, child: repaintBoundary),
configuration: ViewConfiguration(
// size: logicalSize,
logicalConstraints: BoxConstraints(
maxWidth: logicalSize.width,
maxHeight: logicalSize.height,
),
devicePixelRatio: pixelRatio ?? 1.0,
),
);
final PipelineOwner pipelineOwner = PipelineOwner();
final BuildOwner buildOwner = BuildOwner(
focusManager: FocusManager(),
onBuildScheduled: () {
///
///current render is dirty, mark it.
///
isDirty = true;
});
pipelineOwner.rootNode = renderView;
renderView.prepareInitialFrame();
final RenderObjectToWidgetElement<RenderBox> rootElement =
RenderObjectToWidgetAdapter<RenderBox>(
container: repaintBoundary,
child: Directionality(
textDirection: TextDirection.ltr,
child: child,
)).attachToRenderTree(
buildOwner,
);
////
///Render Widget
///
///
buildOwner.buildScope(
rootElement,
);
buildOwner.finalizeTree();
pipelineOwner.flushLayout();
pipelineOwner.flushCompositingBits();
pipelineOwner.flushPaint();
ui.Image? image;
do {
///
///Reset the dirty flag
///
///
isDirty = false;
image = await repaintBoundary.toImage(
pixelRatio: pixelRatio ?? (imageSize.width / logicalSize.width));
///
///This delay sholud increas with Widget tree Size
///
await Future.delayed(delay);
///
///Check does this require rebuild
///
///
if (isDirty) {
///
///Previous capture has been updated, re-render again.
///
///
buildOwner.buildScope(
rootElement,
);
buildOwner.finalizeTree();
pipelineOwner.flushLayout();
pipelineOwner.flushCompositingBits();
pipelineOwner.flushPaint();
}
retryCounter--;
///
///retry untill capture is successfull
///
} while (isDirty && retryCounter >= 0);
try {
/// Dispose All widgets
// rootElement.visitChildren((Element element) {
// rootElement.deactivateChild(element);
// });
buildOwner.finalizeTree();
} catch (e) {}
return image; // Adapted to directly return the image and not the Uint8List
}
///
/// ### This function will calculate the size of your widget and then captures it.
///
/// ## Notes on Usage:
/// 1. Do not use any scrolling widgets like ListView,GridView. Convert those widgets to use Columns and Rows.
/// 2. Do not Widgets like `Flexible`,`Expanded`, or `Spacer`. If you do Please consider passing constraints.
///
/// Params:
///
/// [widget] : The Widget which needs to be captured.
///
/// [delay] : Value for [delay] should increase with widget tree size. Preferred value is 1 seconds
///
/// [context] : parameter is used to Inherit App Theme and MediaQuery data.
///
/// [constraints] : Constraints for your image. Pass this parameter if your widget contains `Scaffold`,`Expanded`,`Flexible`,`Spacer` or any other widget which needs constraint of parent.
///
///
///
Future<Uint8List> captureFromLongWidget(
Widget widget, {
Duration delay = const Duration(seconds: 1),
double? pixelRatio,
BuildContext? context,
BoxConstraints? constraints,
}) async {
ui.Image image = await longWidgetToUiImage(
widget,
delay: delay,
pixelRatio: pixelRatio,
context: context,
constraints: constraints ?? BoxConstraints(),
);
final ByteData? byteData =
await image.toByteData(format: ui.ImageByteFormat.png);
image.dispose();
return byteData!.buffer.asUint8List();
}
Future<ui.Image> longWidgetToUiImage(Widget widget,
{Duration delay = const Duration(seconds: 1),
double? pixelRatio,
BuildContext? context,
BoxConstraints constraints = const BoxConstraints(
maxHeight: double.maxFinite,
)}) async {
final PipelineOwner pipelineOwner = PipelineOwner();
final _MeasurementView rootView =
pipelineOwner.rootNode = _MeasurementView(constraints);
final BuildOwner buildOwner = BuildOwner(focusManager: FocusManager());
final RenderObjectToWidgetElement<RenderBox> element =
RenderObjectToWidgetAdapter<RenderBox>(
container: rootView,
debugShortDescription: 'root_render_element_for_size_measurement',
child: Directionality(
textDirection: TextDirection.ltr,
child: widget,
),
).attachToRenderTree(buildOwner);
try {
rootView.scheduleInitialLayout();
pipelineOwner.flushLayout();
///
/// Calculate Size, and capture widget.
///
return widgetToUiImage(
widget,
targetSize: rootView.size,
context: context,
delay: delay,
pixelRatio: pixelRatio,
);
} finally {
// Clean up.
element
.update(RenderObjectToWidgetAdapter<RenderBox>(container: rootView));
buildOwner.finalizeTree();
}
}
}
class Screenshot extends StatefulWidget {
final Widget? child;
final ScreenshotController controller;
const Screenshot({
Key? key,
required this.child,
required this.controller,
}) : super(key: key);
@override
State<Screenshot> createState() {
return new ScreenshotState();
}
}
class ScreenshotState extends State<Screenshot> with TickerProviderStateMixin {
late ScreenshotController _controller;
@override
void initState() {
super.initState();
_controller = widget.controller;
}
@override
Widget build(BuildContext context) {
return RepaintBoundary(
key: _controller._containerKey,
child: widget.child,
);
}
}
extension Ex on double {
double toPrecision(int n) => double.parse(toStringAsFixed(n));
}
///
/// RenderBox widget to calculate size.
///
class _MeasurementView extends RenderBox
with RenderObjectWithChildMixin<RenderBox> {
final BoxConstraints boxConstraints;
_MeasurementView(this.boxConstraints);
@override
void performLayout() {
assert(child != null);
child!.layout(boxConstraints, parentUsesSize: true);
size = child!.size;
}
@override
void debugAssertDoesMeetConstraints() => true;
}