Flutter:如何 export/save CustomPainter 绘制到字符串坐标或图像 base64?
Flutter: how to export/save a CustomPainter draw to a string coordinates or image base64?
我有一个 CustomPainter,用户必须在其中绘制多条指向图像上各种事物的线条。我需要将所有这些行导出到字符串数组或图像 base64。这可能吗?
我的代码是这样的:
class Signature extends CustomPainter {
List<Offset> points;
Signature({this.points});
@override
void paint(Canvas canvas, Size size) {
Paint paint = new Paint()
..color = Colors.black
..strokeCap = StrokeCap.round
..strokeWidth = 5.0;
for (int i = 0; i < points.length - 1; i++) {
if (points[i] != null && points[i + 1] != null) {
canvas.drawLine(points[i], points[i + 1], paint);
}
canvas.clipRect(Offset.zero & size);
}
}
@override
bool shouldRepaint(Signature oldDelegate) => oldDelegate.points != points;
}
添加图像并听取您制作的 CustomPainter,他们获取渲染并将其转换为 base64 字符串
例如:
// getter canvas to image
Future<ui.Image> get rendered {
var size = context.size;
ui.PictureRecorder recorder = ui.PictureRecorder();
Canvas canvas = Canvas(recorder);
Signature= Signature(points: _points);
painter.paint(canvas, size);
return recorder.endRecording().toImage(size.width.floor(), size.height.floor());
}
// function to convert to String
Future<String> convertCanvasToB64() async {
final img = await rendered;
final pngBytes = await img.toByteData(format: ui.ImageByteFormat.png);
final imgBase64 = base64.encode(pngBytes!.buffer.asUint8List());
return imgBase64;
}
我有一个 CustomPainter,用户必须在其中绘制多条指向图像上各种事物的线条。我需要将所有这些行导出到字符串数组或图像 base64。这可能吗? 我的代码是这样的:
class Signature extends CustomPainter {
List<Offset> points;
Signature({this.points});
@override
void paint(Canvas canvas, Size size) {
Paint paint = new Paint()
..color = Colors.black
..strokeCap = StrokeCap.round
..strokeWidth = 5.0;
for (int i = 0; i < points.length - 1; i++) {
if (points[i] != null && points[i + 1] != null) {
canvas.drawLine(points[i], points[i + 1], paint);
}
canvas.clipRect(Offset.zero & size);
}
}
@override
bool shouldRepaint(Signature oldDelegate) => oldDelegate.points != points;
}
添加图像并听取您制作的 CustomPainter,他们获取渲染并将其转换为 base64 字符串
例如:
// getter canvas to image
Future<ui.Image> get rendered {
var size = context.size;
ui.PictureRecorder recorder = ui.PictureRecorder();
Canvas canvas = Canvas(recorder);
Signature= Signature(points: _points);
painter.paint(canvas, size);
return recorder.endRecording().toImage(size.width.floor(), size.height.floor());
}
// function to convert to String
Future<String> convertCanvasToB64() async {
final img = await rendered;
final pngBytes = await img.toByteData(format: ui.ImageByteFormat.png);
final imgBase64 = base64.encode(pngBytes!.buffer.asUint8List());
return imgBase64;
}