[英]Flutter Image Widget: How to convert the Image widget to Byte array
[英]How to create an image from a widget in Flutter-web?
为了在谷歌地图google_maps_flutter上显示自定义小部件,我使用了一个非常方便的函数,将任何Widget
(包括那些包含图像的Widget
)转换为Image
,然后我将其转换为我需要的Uint8List
。 它适用于 iOS 和 Android。
Future createImageFromWidget( Widget widget){
final RenderRepaintBoundary repaintBoundary = RenderRepaintBoundary();
final RenderView renderView = RenderView(
child: RenderPositionedBox(alignment: Alignment.center, child: repaintBoundary),
configuration: ViewConfiguration(size: const Size.square(300.0), devicePixelRatio: ui.window.devicePixelRatio),
window: null,
);
final PipelineOwner pipelineOwner = PipelineOwner()..rootNode = renderView;
renderView.prepareInitialFrame();
final BuildOwner buildOwner = BuildOwner(focusManager: FocusManager());
final RenderObjectToWidgetElement<RenderBox> rootElement = RenderObjectToWidgetAdapter<RenderBox>(
container: repaintBoundary,
child: Directionality(
textDirection: TextDirection.ltr,
child: IntrinsicHeight(child: IntrinsicWidth(child: widget)),
),
).attachToRenderTree(buildOwner);
buildOwner..buildScope(rootElement)..finalizeTree();
pipelineOwner..flushLayout()..flushCompositingBits()..flushPaint();
return repaintBoundary.toImage(pixelRatio: ui.window.devicePixelRatio)
.then((image) => image.toByteData(format: ui.ImageByteFormat.png))
.then((byteData) => byteData.buffer.asUint8List());
}
但不幸的是,当我尝试在 Web 上使用此功能时,出现以下错误:
不支持的操作:Web 上不支持 toImage
现在 Flutter 支持Image.toByteData
和Picture.toImage
#20750 ,但我不知道如何在我的情况下使用它。
实际上问题是 - 如何重新制作此功能以便它也可以在 Web 上运行?
谢谢,我会很高兴有任何想法
repaintBoundary.toImage
功能依赖于Scene.toImage
,根据问题#42767 中的评论尚未为 Web 实现。
这个问题目前也没有被优先考虑。
如果您将--dart-define=FLUTTER_WEB_USE_SKIA
放在flutter build web
参数上, toImage() 就可以工作。
该方法在没有此参数的情况下在本地工作。
我在看到crop包文档后找到了这个解决方案,它也使用了 toImage()
编辑
我在通过 iPhone 访问应用程序时发现了一些问题,从小部件生成图像可以正常工作,但是我在项目中的一些动画停止工作。
我发现了这个问题,我将仅使用参数--dart-define=FLUTTER_WEB_AUTO_DETECT=true
进行一些测试,以查看是否可以在桌面、android 和 iOS 上正确使用 Flutter web。
编辑 2
在 MacO 上进行一些测试后, toImage() 方法也可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.