toImage method

Future<Image?> toImage({
  1. int? width,
  2. int? height,
})

Convert to an Image. Will return null if there are no points.

Implementation

Future<ui.Image?> toImage({int? width, int? height}) async {
  if (isEmpty) {
    return null;
  }

  final ui.PictureRecorder recorder = ui.PictureRecorder();
  final ui.Canvas canvas = Canvas(recorder)
    ..translate(-(minXValue! - penStrokeWidth), -(minYValue! - penStrokeWidth));
  if (exportBackgroundColor != null) {
    final ui.Paint paint = Paint()..color = exportBackgroundColor!;
    canvas.drawPaint(paint);
  }
  if (width != null || height != null) {
    assert(
      ((width ?? defaultWidth!) - defaultWidth!) >= 0.0,
      'Exported width cannot be smaller than actual width',
    );
    assert(
      ((height ?? defaultHeight!) - defaultHeight!) >= 0.0,
      'Exported height cannot be smaller than actual height',
    );
    //IF WIDTH OR HEIGHT IS SPECIFIED WE NEED TO CENTER DRAWING
    //WE WILL MOVE THE DRAWING BY HALF OF THE REMAINING SPACE IF
    //IF DIMENSION IS NOT SPECIFIED WE WILL DEFAULT TO ACTUAL
    //SIZE OF THE DRAWING HENCE THE DIFFERENCE WILL BE ZERO
    //AND DRAWING WILL NOT MOVE IN THAT DIRECTION
    canvas.translate(
      ((width ?? defaultWidth!) - defaultWidth!).toDouble() / 2,
      ((height ?? defaultHeight!) - defaultHeight!).toDouble() / 2,
    );
  }
  _SignaturePainter(this, penColor: exportPenColor).paint(
    canvas,
    Size.infinite,
  );
  final ui.Picture picture = recorder.endRecording();
  return picture.toImage(width ?? defaultWidth!, height ?? defaultHeight!);
}