一尘不染

Flutter:如何将Canvas / CustomPainter保存到图像文件?

flutter

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

这是我到目前为止的内容:

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;
}

不知道从那里去哪里…


阅读 1224

收藏
2020-08-13

共1个答案

一尘不染

您可以捕获的输出CustomPainterPictureRecorder。将PictureRecorder实例传递给的构造函数Canvas。在Picture通过返回PictureRecorder.endRecording然后可以转化为ImagePicture.toImage。最后,使用提取图像字节Image.toByteData

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

2020-08-13