美文网首页
Flutter-涂鸦CustomPainter

Flutter-涂鸦CustomPainter

作者: 秋分落叶 | 来源:发表于2019-04-09 14:49 被阅读0次

    先看一下效果

    具体代码如下:

    import 'package:flutter/material.dart';

    void main() => runApp(MyApp());

    class MyApp extends StatefulWidget {

      @override

      _MyAppState createState() => _MyAppState();

    }

    class _MyAppState extends State<MyApp> {

      List<Offset> _points = List<Offset>();

      @override

      Widget build(BuildContext context) {

        return MaterialApp(

          home: Scaffold(

            body: Container(

              child: GestureDetector(

                onPanUpdate: (DragUpdateDetails details){

                  setState((){

                    RenderBox obj = context.findRenderObject();

                    Offset _localPosition = obj.globalToLocal(details.globalPosition);

                    _points = List.from(_points)..add(_localPosition);

                  });

                },

                onPanEnd: (DragEndDetails details) => _points..add(null),

                child: CustomPaint(

                  painter: Signature(_points),

                  size: Size.infinite,

                ),

              ),

            ),

            floatingActionButton: FloatingActionButton(

              child: Icon(Icons.clear),

              onPressed: () => _points.clear(),

            ),

          ),

        );

      }

    }

    class Signature extends CustomPainter {

      List<Offset> points;

      Signature(this.points);

      @override

      void paint(Canvas canvas, Size size) {

        Paint paint = Paint()

        ..color = Colors.black

        ..strokeCap = StrokeCap.round

        ..strokeWidth = 5;

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

          }

        }

      }

      @override

      bool shouldRepaint(Signature oldDelegate) => oldDelegate.points != points;

    }

    相关文章

      网友评论

          本文标题:Flutter-涂鸦CustomPainter

          本文链接:https://www.haomeiwen.com/subject/dvwbiqtx.html