从Flutter Widget获取PNG文件,而无需绘制到屏幕



我有一个有点像《world》的游戏,我想添加一个像《world》那样的共享功能。我的游戏网格小部件上有一个标志,允许我渲染正常显示的版本,或用于共享的特殊版本。我想使用小部件来获取PNG文件(或PNG字节数据)。我宁愿不把它实际绘制到屏幕上,只是渲染到一些framebuffer并转换为PNG,尽管渲染到屏幕是可以的,如果替代方案是不可能的。通过文档,它不明显是否我试图做什么是可能的,甚至是有意义的(似乎我可能要得到小部件实例化为一个元素,然后得到一个渲染对象,这似乎意味着必须把它放在我的布局和绘制到显示),但也许我错过了一些东西。有办法做到这一点吗?

您可能想看看flutter的screenshot包。

将小部件捕获为图像的简单包。现在,您还可以捕获未在屏幕上呈现的小部件!

1。创建截图控制器实例

class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
Uint8List _imageFile;
//Create an instance of ScreenshotController
ScreenshotController screenshotController = ScreenshotController(); 
@override
void initState() {
// TODO: implement initState
super.initState();
}
...
}

2。将要捕获的小部件包装在屏幕截图小部件中。将控制器分配给先前创建的screenshotController

Screenshot(
controller: screenshotController,
child: Text("This text will be captured as image"),
),

3。通过调用capture方法获取截图。这将返回一个Uint8List

screenshotController.capture().then((Uint8List image) {
//Capture Done
setState(() {
_imageFile = image;
});
}).catchError((onError) {
print(onError);
});

Extra:将图像保存到指定位置

final directory = (await getApplicationDocumentsDirectory ()).path; //from path_provide package
String fileName = DateTime.now().microsecondsSinceEpoch;
path = '$directory';
screenshotController.captureAndSave(
path //set path where screenshot will be saved
fileName:fileName 
);
参考下面的例子

我曾经开发过一个应用,我需要一些类似的东西。搜索了一段时间后,我发现了一个名为"截图"的包

此包允许您将可见或不可见的小部件转换为图像。

下面是他们文档

中的示例代码
ScreenshotController screenshotController = ScreenshotController();
function createScreenshot(){
screenshotController
.captureFromWidget(Container(
padding: const EdgeInsets.all(30.0),
decoration: BoxDecoration(
border: Border.all(color: Colors.blueAccent, width: 5.0),
color: Colors.redAccent,
),
child: Text("This is an invisible widget"),
),
).then((capturedImage) {
// Here you will get image object
});
}

最新更新