Flutter: How would one save a Canvas/CustomPainter to an image file?

前端 未结 2 402
时光说笑
时光说笑 2020-12-15 07:58

I am trying to collect a signature from the user and save it to an image. I have made it far enough that I can draw on the screen, but now I\'d like to click a button to sav

2条回答
  •  天命终不由人
    2020-12-15 08:15

    Add the rendered method in your widget

      ui.Image get rendered {
        // [CustomPainter] has its own @canvas to pass our
        // [ui.PictureRecorder] object must be passed to [Canvas]#contructor
        // to capture the Image. This way we can pass @recorder to [Canvas]#contructor
        // using @painter[SignaturePainter] we can call [SignaturePainter]#paint
        // with the our newly created @canvas
        ui.PictureRecorder recorder = ui.PictureRecorder();
        Canvas canvas = Canvas(recorder);
        SignaturePainter painter = SignaturePainter(points: _points);
        var size = context.size;
        painter.paint(canvas, size);
        return recorder.endRecording()
            .toImage(size.width.floor(), size.height.floor());
      }
    

    Then using state fetch the rendered image

    var image = signatureKey.currentState.rendered
    

    Now, you can produce png Image using toByteData(format: ui.ImageByteFormat.png) and store using asInt8List()

    var pngBytes = await image.toByteData(format: ui.ImageByteFormat.png)
    File('your-path/filename.png')
        .writeAsBytesSync(pngBytes.buffer.asInt8List())
    

    For complete example, on how to export canvas as png check out this example https://github.com/vemarav/signature

提交回复
热议问题