Skip to content

Instantly share code, notes, and snippets.

@MacDeveloper1
Created February 14, 2024 10:35
Show Gist options
  • Save MacDeveloper1/006e0ad342a8df385d5c752abe20335c to your computer and use it in GitHub Desktop.
Save MacDeveloper1/006e0ad342a8df385d5c752abe20335c to your computer and use it in GitHub Desktop.
test
/// Provides a functionality for capture the widget as image.
class WidgetToImage {
WidgetToImage._();
/// Captures the widget.
///
/// The [pixelRatio] describes the scale between the logical pixels and the
/// size of the output image. It is independent of the
/// [dart:ui.FlutterView.devicePixelRatio] for the device, so specifying 1.0
/// (the default) will give you a 1:1 mapping between logical pixels and the
/// output pixels in the image.
static Future<Uint8List> capture(
Widget widget, {
BuildContext? context,
double pixelRatio = 1.0,
Duration buildDelay = Duration.zero,
/// Converts the [Image] object into a byte array.
///
/// The [format] argument specifies the format in which the bytes will be
/// returned.
ui.ImageByteFormat format = ui.ImageByteFormat.png,
}) async {
final flutterView = context != null
? View.of(context)
: PlatformDispatcher.instance.views.first;
final logicalSize = flutterView.physicalSize / flutterView.devicePixelRatio;
final widgetSize = flutterView.physicalSize;
assert(logicalSize.aspectRatio == widgetSize.aspectRatio);
final renderRepaintBoundary = RenderRepaintBoundary();
final renderView = RenderView(
view: flutterView,
child: RenderPositionedBox(
child: renderRepaintBoundary,
),
configuration: ViewConfiguration(
size: logicalSize,
devicePixelRatio: pixelRatio,
),
);
final pipelineOwner = PipelineOwner()..rootNode = renderView;
renderView.prepareInitialFrame();
final buildOwner = BuildOwner(
focusManager: FocusManager(),
onBuildScheduled: () {},
);
final rootElement = RenderObjectToWidgetAdapter(
container: renderRepaintBoundary,
child: Directionality(
textDirection: TextDirection.ltr,
child: widget,
),
).attachToRenderTree(buildOwner);
buildOwner
..buildScope(rootElement)
..finalizeTree();
pipelineOwner
..flushLayout()
..flushCompositingBits()
..flushPaint();
if (buildDelay.inMicroseconds > 0) await Future.delayed(buildDelay);
final image = await renderRepaintBoundary.toImage(pixelRatio: pixelRatio);
final byteData = await image.toByteData(format: format);
image.dispose();
return byteData!.buffer.asUint8List();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment