flutter - 无法在颤动中截取屏幕截图
问题描述
包:flutter/src/rendering/proxy_box.dart':断言失败:第 2813 行 pos 12:'!debugNeedsPaint':不正确。
我试图在颤动中截取屏幕截图,但我遇到了异常。我访问了许多链接,但没有任何效果。
Future<Uint8List> _capturePng() async {
try {
print('inside');
RenderRepaintBoundary boundary = _globalKey.currentContext.findRenderObject();
ui.Image image = await boundary.toImage(pixelRatio: 3.0);
ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
var pngBytes = byteData.buffer.asUint8List();
var bs64 = base64Encode(pngBytes);
print(pngBytes);
print(bs64);
setState(() {});
return pngBytes;
} catch (e) {
print(e);
}
}
解决方案
您可以在此处找到官方toImage
示例。但看起来它在按钮点击和呼叫之间没有延迟就无法工作。toImage
官方仓库有问题:https ://github.com/flutter/flutter/issues/22308
造成这种情况的原因:您的点击初始化按钮的动画并被包括父母在内的递归调用,因此您应该再次RenderObject.markNeedsPaint
等待。在这种情况下,函数只会抛出断言错误:debugNeedsPaint
false
toImage
Future<ui.Image> toImage({ double pixelRatio = 1.0 }) {
assert(!debugNeedsPaint);
final OffsetLayer offsetLayer = layer;
return offsetLayer.toImage(Offset.zero & size, pixelRatio: pixelRatio);
}
bool get debugNeedsPaint {
bool result;
assert(() {
result = _needsPaint;
return true;
}());
return result;
}
实际上assert
函数只在开发中使用,所以你可以看到你不会在生产中遇到错误的麻烦。但是我不知道您会遇到什么样的麻烦,可能没有)。
下一个代码不是很好,但它可以工作:
class _MyHomePageState extends State<MyHomePage> {
GlobalKey globalKey = GlobalKey();
Future<Uint8List> _capturePng() async {
RenderRepaintBoundary boundary = globalKey.currentContext.findRenderObject();
if (boundary.debugNeedsPaint) {
print("Waiting for boundary to be painted.");
await Future.delayed(const Duration(milliseconds: 20));
return _capturePng();
}
var image = await boundary.toImage();
var byteData = await image.toByteData(format: ImageByteFormat.png);
return byteData.buffer.asUint8List();
}
void _printPngBytes() async {
var pngBytes = await _capturePng();
var bs64 = base64Encode(pngBytes);
print(pngBytes);
print(bs64);
}
@override
Widget build(BuildContext context) {
return RepaintBoundary(
key: globalKey,
child: Center(
child: FlatButton(
color: Color.fromARGB(255, 255, 255, 255),
child: Text('Capture Png', textDirection: TextDirection.ltr),
onPressed: _printPngBytes
),
),
);
}
}
推荐阅读
- python - Pandas 创建多列数的 DataFrame
- c++ - 与 C++ 原子内存栅栏同步
- regex - 正则表达式替换斜杠和空格之间的所有内容
- r - 在R中使用循环函数来计算沉降率?
- java - 如何为 jackson-dataype-hal 注释记录
- java - 如果我手动关闭它,程序只写入文件?
- javascript - AWS AppSync Graphql Subsciprtion - 如果订阅的输入在 Mutation 的列表中,则触发订阅
- c++ - 无法转换字符串插入函数的参数
- javascript - 带有输出到 Flask forloop 的 Python API 调用
- r - 找到特定时间段的最小值;如果此最小值为 NA,请使用之前的日期