首页 > 解决方案 > 如何从使用 CustomPainter 绘制的画布中获取图像?

问题描述

在我的 Flutter 应用程序中,我使用CustomPainter来允许用户在屏幕上绘制他们的签名。我需要找到一种方法将其保存为图像。

当您能够PictureRecorder按照之前的 StackOverflow 答案将对象传递到画布时, PictureRecorder可以很好地工作:

final recorder = new PictureRecorder();
Canvas(recorder).drawSomething;
final picture = recorder.endRecording();

然而,当使用CustomPainter画布时是Paint()函数的一个参数。

class myPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    drawToCanvas(canvas);

  @override
  bool shouldRepaint(CustomPainter old) {
    return false; 
}

总而言之:

如何从 CustomPainter 生成图像?
如果答案是使用 PictureRecorder,我怎样才能将记录器传递给画布?

标签: imagecanvasdartfluttercustom-painting

解决方案


您不需要PictureRecorder在方法中将 传递给画布CustomPainter paint。相反,您可以使用具有图片记录器的不同画布直接调用绘画。例如:

Future<Image> getImage() async {
final PictureRecorder recorder = PictureRecorder();
myPainter.paint(Canvas(recorder), mySize);
final Picture picture = recorder.endRecording();

return await picture.toImage(width, height);
}


推荐阅读