Flutter画板实现

作者: TryEnough | 来源:发表于2019-01-29 17:57 被阅读4次

    原文链接

    更多教程


    效果

    代码

    import 'package:flutter/material.dart';
    
    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;
    }
    
    class Signature extends StatefulWidget {
      SignatureState createState() => new SignatureState();
    }
    
    class SignatureState extends State<Signature> {
      List<Offset> _points = <Offset>[];
    
      Widget build(BuildContext context) {
        return new Stack(
          children: [
            GestureDetector(
              onPanUpdate: (DragUpdateDetails details) {
                RenderBox referenceBox = context.findRenderObject();
                Offset localPosition =
                referenceBox.globalToLocal(details.globalPosition);
    
                setState(() {
                  _points = new List.from(_points)..add(localPosition);
                });
              },
              onPanEnd: (DragEndDetails details) => _points.add(null),
            ),
            CustomPaint(painter: new SignaturePainter(_points))
          ],
        );
      }
    }
    
    class DemoApp extends StatelessWidget {
      Widget build(BuildContext context) => new Scaffold(body: new Signature());
    }
    
    void main() => runApp(new MaterialApp(home: new DemoApp()));
    

    原文链接

    更多教程

    相关文章

      网友评论

        本文标题:Flutter画板实现

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