我有一个Flutter小部件,它接受用户输入并使用自定义画家绘制到画布:
class SPPoint {
final Point point;
final double size;
SPPoint(this.point, this.size);
String toString() => "SPPoint $point $size";
}
class SignaturePadPainter extends CustomPainter {
final List<SPPoint> allPoints;
final SignaturePadOptions opts;
Canvas _lastCanvas;
Size _lastSize;
SignaturePadPainter(this.allPoints, this.opts);
ui.Image getPng() {
if (_lastCanvas == null) {
return null;
}
if (_lastSize == null) {
return null;
}
var recorder = new ui.PictureRecorder();
var origin = new Offset(0.0, 0.0);
var paintBounds = new Rect.fromPoints(_lastSize.topLeft(origin), _lastSize.bottomRight(origin));
var canvas = new Canvas(recorder, paintBounds);
paint(canvas, _lastSize);
var picture = recorder.endRecording();
return picture.toImage(_lastSize.width.round(), _lastSize.height.round());
}
paint(Canvas canvas, Size size) {
_lastCanvas = canvas;
_lastSize = size;
for (var point in this.allPoints) {
var paint = new Paint()..color = colorFromColorString(opts.penColor);
paint.strokeWidth = 5.0;
var path = new Path();
var offset = new Offset(point.point.x, point.point.y);
path.moveTo(point.point.x, point.point.y);
var pointSize = point.size;
if (pointSize == null || pointSize.isNaN) {
pointSize = opts.dotSize;
}
canvas.drawCircle(offset, pointSize, paint);
paint.style = PaintingStyle.stroke;
canvas.drawPath(path, paint);
}
}
bool shouldRepaint(SignaturePadPainter oldDelegate) {
return true;
}
}
目前当前getPng()
会返回一个dart:ui Image对象,但我无法告诉如何从图像数据中获取字节(如果可能的话)
答案 0 :(得分:1)
这是我想出的解决方案,因为toByteData()
已添加到SDK:
var picture = recorder.endRecording();
var image =
picture.toImage(lastSize.width.round(), lastSize.height.round());
ByteData data = await image.toByteData(format: ui.ImageByteFormat.png);
return data.buffer.asUint8List();
此解决方案正在运行,并且已作为signature_pad_flutter软件包的一部分发布到发布商:https://github.com/apptreesoftware/signature-pad-dart/blob/master/signature_pad_flutter/lib/src/painter.dart#L17