Android

关注公众号 jb51net

关闭
首页 > 软件编程 > Android > Flutter手写签名效果

如何使用Flutter实现手写签名效果

作者:Jerry815

Flutter插件提供了用于绘制平滑签名的签名板,下面这篇文章主要给大家介绍了关于如何使用Flutter实现手写签名效果的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下

思路

绘制流程

具体实现

需要一个Listener用来监听用户行为,并将这些行为的点添加到StreamController中, 两个变量

final List _points = []; //承载对应的点
final StreamController _controller = StreamController(); //数据通信

Widget _buildWriteWidget() {
  return Stack(
    children: [
      Listener( //用来监听用户的触摸行为
        child: Container(
          color: Colors.transparent,
        ),
        onPointerDown: (PointerDownEvent event) {
          _points.add(event.localPosition);
          _controller.sink.add([_points]);  //起始点的记录
        },
        onPointerMove: (PointerMoveEvent event) {
          _points.add(event.localPosition);
          _controller.sink.add([_points]);  //添加途经点
        },
        onPointerUp: (PointerUpEvent event) {
          _points.add(Offset.zero); //结束的标记
        },
      ),
      StreamBuilder(
          stream: _controller.stream,
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            return snapshot.hasData
                ? CustomPaint(painter: LinePainter(snapshot.data))  //关联数据到Painter
                : const SizedBox();
          }),
      Positioned(
          bottom: 50,
          right: 50,
          child: FloatingActionButton(
            onPressed: () {
              _clear();
            },
            child: const Icon(Icons.cleaning_services),
          ))
    ],
  );
}

清除StreamController的内容,重置数据

void _clear() {
  _points.clear();
  _controller.add(null);
}

dispose时释放StreamController

@override
void dispose() {
  _controller.close();
  super.dispose();
}

画笔Painter

class LinePainter extends CustomPainter {
  final List<List<Offset>> lines;
  final Color paintColor = Colors.black;
  final Paint _paint = Paint();

  LinePainter(this.lines);

  @override
  void paint(Canvas canvas, Size size) {
    _paint.strokeCap = StrokeCap.round;
    _paint.strokeWidth = 5.0;
    if (lines.isEmpty) {
      canvas.drawPoints(PointMode.polygon, [Offset.zero, Offset.zero], _paint);
    } else {
      for (int i = 0; i < lines.length; i++) {
        for (int j = 0; j < lines[i].length - 1; j++) {
          if (lines[i][j] != Offset.zero && lines[i][j + 1] != Offset.zero) {
            canvas.drawLine(lines[i][j], lines[i][j + 1], _paint);  //绘制相应的点
          }
        }
      }
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}

总结

到此这篇关于如何使用Flutter实现手写签名效果的文章就介绍到这了,更多相关Flutter手写签名效果内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

阅读全文