Joh*_*ohn 12 dart flutter flutter-animation
考虑到 Flutter 使用自己的图形引擎,有没有办法将 Flutter 动画直接渲染到视频中,或者以逐帧的方式创建屏幕截图?
一个用例是,这可以让观众更轻松地进行演示。
例如,一位作者想要创建一个 Flutter 动画教程,他们在其中构建了一个演示应用程序并撰写了一篇配套博客文章,使用直接用 Flutter 渲染的动画 GIF/视频。
另一个例子是 UI 团队之外的一位开发人员发现一个复杂的动画有一个小错误。无需实际学习动画代码,他们就可以将动画渲染成视频并使用注释编辑该短片,然后将其发送给 UI 团队进行诊断。
它并不漂亮,但我已经设法让原型工作。首先,所有动画都需要由一个主动画控制器驱动,以便我们可以逐步执行我们想要的动画的任何部分。其次,我们要记录的小部件树必须用RepaintBoundary
全局键包裹在 a 中。RepaintBoundary 及其键可以生成小部件树的快照,如下所示:
Future<Uint8List> _capturePngToUint8List() async {
// renderBoxKey is the global key of my RepaintBoundary
RenderRepaintBoundary boundary = renderBoxKey.currentContext.findRenderObject();
// pixelratio allows you to render it at a higher resolution than the actual widget in the application.
ui.Image image = await boundary.toImage(pixelRatio: 2.0);
ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
Uint8List pngBytes = byteData.buffer.asUint8List();
return pngBytes;
}
Run Code Online (Sandbox Code Playgroud)
然后可以在循环中使用上述方法,该循环将小部件树捕获到 pngBytes 中,并通过由您想要的帧率指定的 deltaT 使 animationController 向前步进,如下所示:
double t = 0;
int i = 1;
setState(() {
animationController.value = 0.0;
});
Map<int, Uint8List> frames = {};
double dt = (1 / 60) / animationController.duration.inSeconds.toDouble();
while (t <= 1.0) {
print("Rendering... ${t * 100}%");
var bytes = await _capturePngToUint8List();
frames[i] = bytes;
t += dt;
setState(() {
animationController.value = t;
});
i++;
}
Run Code Online (Sandbox Code Playgroud)
最后,所有这些 png 帧都可以通过管道传输到 ffmpeg 子进程以写入视频。我还没有设法让这部分工作得很好,所以我所做的是将所有 png 帧写出到实际的 png 文件中,然后我在写入它们的文件夹中手动运行 ffmpeg。(注意:我已经使用 flutter desktop 来访问我安装的 ffmpeg,但是pub.dev 上也有一个包可以在移动设备上获取 ffmpeg)
double t = 0;
int i = 1;
setState(() {
animationController.value = 0.0;
});
Map<int, Uint8List> frames = {};
double dt = (1 / 60) / animationController.duration.inSeconds.toDouble();
while (t <= 1.0) {
print("Rendering... ${t * 100}%");
var bytes = await _capturePngToUint8List();
frames[i] = bytes;
t += dt;
setState(() {
animationController.value = t;
});
i++;
}
Run Code Online (Sandbox Code Playgroud)
这是我的文件编写器帮助功能:
Future<File> _writeFile({@required String location, @required Uint8List bytes}) async {
File file = File(location);
return file.writeAsBytes(bytes);
}
Run Code Online (Sandbox Code Playgroud)
这是我的 FFmpeg runner 函数:
List<Future<File>> fileWriterFutures = [];
frames.forEach((key, value) {
fileWriterFutures.add(_writeFile(bytes: value, location: r"D:\path\to\my\images\folder\" + "frame_$key.png"));
});
await Future.wait(fileWriterFutures);
_runFFmpeg();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1663 次 |
最近记录: |