如何从使用 CustomPainter 绘制的 canvas 中获取图像?
How to get an image from a canvas drawn with CustomPainter?
在我的 Flutter 应用程序中,我使用 CustomPainter 允许用户在屏幕上绘制他们的签名。我需要找到一种方法将其另存为图像。
PictureRecorder works nicely when you are able to pass the PictureRecorder
object to the canvas as per :
final recorder = new PictureRecorder();
Canvas(recorder).drawSomething;
final picture = recorder.endRecording();
然而,当使用 CustomPainter
时,canvas 是 Paint()
函数的参数。
class myPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
drawToCanvas(canvas);
@override
bool shouldRepaint(CustomPainter old) {
return false;
}
总而言之:
如何从 CustomPainter 生成图像?
如果答案是使用 PictureRecorder,我如何将记录器传递给 canvas?
您不需要在 CustomPainter
paint
方法中将 PictureRecorder
传递给 canvas。相反,您可以使用具有图片记录器的不同 canvas 直接调用绘画。例如:
Future<Image> getImage() async {
final PictureRecorder recorder = PictureRecorder();
myPainter.paint(Canvas(recorder), mySize);
final Picture picture = recorder.endRecording();
return await picture.toImage(width, height);
}
在我的 Flutter 应用程序中,我使用 CustomPainter 允许用户在屏幕上绘制他们的签名。我需要找到一种方法将其另存为图像。
PictureRecorder works nicely when you are able to pass the PictureRecorder
object to the canvas as per
final recorder = new PictureRecorder();
Canvas(recorder).drawSomething;
final picture = recorder.endRecording();
然而,当使用 CustomPainter
时,canvas 是 Paint()
函数的参数。
class myPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
drawToCanvas(canvas);
@override
bool shouldRepaint(CustomPainter old) {
return false;
}
总而言之:
如何从 CustomPainter 生成图像?
如果答案是使用 PictureRecorder,我如何将记录器传递给 canvas?
您不需要在 CustomPainter
paint
方法中将 PictureRecorder
传递给 canvas。相反,您可以使用具有图片记录器的不同 canvas 直接调用绘画。例如:
Future<Image> getImage() async {
final PictureRecorder recorder = PictureRecorder();
myPainter.paint(Canvas(recorder), mySize);
final Picture picture = recorder.endRecording();
return await picture.toImage(width, height);
}