Flutter 手势监听和画板实现

直接代码环节

核心逻辑就是监听用户手势,然后使用drawPath的方式,来绘制用户的手势路径

代码里都有注释,后面可以自定义画笔颜色和画笔粗细

import 'package:flutter/material.dart';

///画板的实现逻辑
///
///首先是绘制部分
///想法是使用path的方式,也就是两个点
///一个是moveTo,一个是lineTo
///
/// 手势部分,
/// 监听手指落下,和手指抬起即可
class CanvasPage extends StatefulWidget {
  const CanvasPage({Key? key}) : super(key: key);

  @override
  State createState() => _CanvasPageState();
}

class _CanvasPageState extends State {
  Path path = Path();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('手势监听+画板')),
      body: Listener(
        ///落下
        onPointerDown: (p) {
          path.moveTo(p.localPosition.dx, p.localPosition.dy);
          setState(() {});
        },
        ///移动
        onPointerMove: (p) {
          path.lineTo(p.localPosition.dx, p.localPosition.dy);
          setState(() {});
        },
        ///离开
        onPointerUp: (p) {
          path.moveTo(p.localPosition.dx, p.localPosition.dy);
          path.close();
          setState(() {});
        },
        child: CustomPaint(
          foregroundPainter: CanvasPaint(path: path),
          child: Container(
            color: Colors.transparent,
          ),
        ),
      ),
    );
  }
}

class CanvasPaint extends CustomPainter {
  Path? path;
  ///画笔颜色
  Color? color;
  ///画笔粗细
  double? width;

  CanvasPaint(
      {required this.path, this.color = Colors.black, this.width = 5.0});

  @override
  void paint(Canvas canvas, Size size) {
    canvas.drawColor(Colors.transparent, BlendMode.color);
    Paint paint = Paint()
      ..color = color!
      ..strokeWidth = width!
      ..style = PaintingStyle.stroke;
    canvas.drawPath(path!, paint);
  }

  ///是否需要重新绘制
  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}

效果图

Flutter 手势监听和画板实现_第1张图片

 

你可能感兴趣的:(flutter,android)