它并不漂亮,但我已经设法让原型工作了。首先,所有动画都需要由一个主动画控制器提供支持,以便我们可以单步执行我们想要的动画的任何部分。其次,我们要记录的小部件树必须用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;
}
然后可以在循环中使用上述方法,该循环将小部件树捕获到 pngBytes 中,并通过您想要的帧速率指定的 deltaT 将动画控制器向前步进:
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++;
}
最后,所有这些 png 帧都可以通过管道传输到 ffmpeg 子进程中以写入视频。我还没有设法让这部分工作得很好,所以我所做的是将所有的 png 帧写入实际的 png 文件,然后我在写入它们的文件夹中手动运行 ffmpeg。(注意:我使用 Flutter 桌面能够访问我安装的 ffmpeg,但是pub.dev 上有一个包也可以在移动设备上获取 ffmpeg)
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();
这是我的文件编写器帮助功能:
Future<File> _writeFile({@required String location, @required Uint8List bytes}) async {
File file = File(location);
return file.writeAsBytes(bytes);
}
这是我的 FFmpeg 运行器功能:
void _runFFmpeg() async {
// ffmpeg -y -r 60 -start_number 1 -i frame_%d.png -c:v libx264 -preset medium -tune animation -pix_fmt yuv420p test.mp4
var process = await Process.start(
"ffmpeg",
[
"-y", // replace output file if it already exists
"-r", "60", // framrate
"-start_number", "1",
"-i", r"./test/frame_%d.png", // <- Change to location of images
"-an", // don't expect audio
"-c:v", "libx264rgb", // H.264 encoding
"-preset", "medium",
"-crf",
"10", // Ranges 0-51 indicates lossless compression to worst compression. Sane options are 0-30
"-tune", "animation",
"-preset", "medium",
"-pix_fmt", "yuv420p",
r"./test/test.mp4" // <- Change to location of output
],
mode: ProcessStartMode.inheritStdio // This mode causes some issues at times, so just remove it if it doesn't work. I use it mostly to debug the ffmpeg process' output
);
print("Done Rendering");
}