Flutter:如何将 Canvas/CustomPainter 保存到图像文件中? [英] Flutter: How would one save a Canvas/CustomPainter to an image file?

查看:75
本文介绍了Flutter:如何将 Canvas/CustomPainter 保存到图像文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从用户那里收集签名并将其保存到图像中.我已经做到了可以在屏幕上绘图的距离,但现在我想单击一个按钮以保存到图像并存储在我的数据库中.

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 save to an image and store in my database.

这是我目前所拥有的:

import 'package:flutter/material.dart';

class SignaturePadPage extends StatefulWidget {
  SignaturePadPage({Key key}) : super(key: key);

  @override
  _SignaturePadPage createState() => new _SignaturePadPage();
}
class _SignaturePadPage extends State<SignaturePadPage> {

  List<Offset> _points = <Offset>[];

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: GestureDetector(
        onPanUpdate: (DragUpdateDetails details) {
          setState(() {
            RenderBox referenceBox = context.findRenderObject();
            Offset localPosition =
            referenceBox.globalToLocal(details.globalPosition);
            _points = new List.from(_points)..add(localPosition);
          });
        },
        onPanEnd: (DragEndDetails details) => _points.add(null),
        child: new CustomPaint(painter: new SignaturePainter(_points)),
      ),
    );
  }
}

class SignaturePainter extends CustomPainter {
  SignaturePainter(this.points);
  final List<Offset> points;
  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);
    }
  }
  bool shouldRepaint(SignaturePainter other) => other.points != points;
}

不知道从那里去哪里......

Not sure where to go from there...

推荐答案

您可以捕获 CustomPainterPictureRecorder.将您的 PictureRecorder 实例传递给Canvas 的构造函数.Picture 返回的 href="https://docs.flutter.io/flutter/dart-ui/PictureRecorder/endRecording.html" rel="noreferrer">PictureRecorder.endRecording 然后可以转换为ImagePicture.toImage.最后,使用 Image.toByteData 提取图像字节.

You can capture the output of a CustomPainter with PictureRecorder. Pass your PictureRecorder instance to the constructor for your Canvas. The Picture returned by PictureRecorder.endRecording can then be converted to an Image with Picture.toImage. Finally, extract the image bytes using Image.toByteData.

这是一个例子:https://github.com/rxlabz/flutter_canvas_to_image

这篇关于Flutter:如何将 Canvas/CustomPainter 保存到图像文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆