美文网首页
Flutter canvas刮刮乐

Flutter canvas刮刮乐

作者: 倪大头 | 来源:发表于2022-11-18 11:20 被阅读0次
211_1668739627.gif

利用canvas画布给“刮奖区”上面盖一层蒙板,再利用Paint画笔的BlendMode.clear属性,把canvas上的蒙板擦掉

Listener(
        onPointerDown: (PointerDownEvent event) {
          
        },
        onPointerUp: (PointerUpEvent event) {
          
        },
        onPointerCancel: (PointerCancelEvent event) {
          
        },
        onPointerMove: (PointerMoveEvent event) {
          
        },
        child: RepaintBoundary(
          child: CustomPaint(
            foregroundPainter: MyPainter(pointsNotifier),
            child: Container(
              width: width,
              height: height,
              color: Colors.redAccent,
              alignment: Alignment.center,
              child: Text(
                '再来一瓶',
                style: TextStyle(
                  fontSize: 28,
                  fontWeight: FontWeight.bold,
                  color: Colors.yellow,
                ),
              ),
            ),
          ),
        ),
      )

foregroundPainter是前景画板,蒙层的绘制就在前景画板上

画布外面套了一层Listener,用来监听刮奖的手势,方便在蒙板上画“透明”的线,而RepaintBoundary可以避免因各种父组件造成的过多的重绘。

Canvas画板要根据手势进行画线和实时刷新,先准备一个ValueNotifier和Point类:

enum PointType {
  tap,
  move,
}

class Point {
  Offset offset;
  PointType type;

  Point(this.offset, this.type);
}

class PointsNotifier extends ValueNotifier<List<Point>> {
  PointsNotifier({List<Point>? points}) : super(points ?? <Point>[]);

  void addPoint(Point point) {
    value.add(point);
    notifyListeners();
  }
}

PointsNotifier继承自ValueNotifier,我们可以手动notifyListeners,完成刷新通知,如果直接用ValueNotifier监听List,List的add不会触发刷新,必须给List重新赋值才行
比如下面的方式不会触发刷新:

ValueNotifier<List<Point>> points = ValueNotifier([]);
points.add(Point(offset, type));

这样才会触发:

ValueNotifier<List<Point>> points = ValueNotifier([]);
points = otherPoints;

接下来在手势监听回调中修改Point列表数据:

onPointerDown: (PointerDownEvent event) {
    pointsNotifier.addPoint(Point(
      event.localPosition,
      PointType.tap,
    ));
},
onPointerUp: (PointerUpEvent event) {
    pointsNotifier.addPoint(Point(
      event.localPosition,
      PointType.tap,
    ));
},
onPointerCancel: (PointerCancelEvent event) {
    pointsNotifier.addPoint(Point(
      event.localPosition,
      PointType.tap,
    ));
},
onPointerMove: (PointerMoveEvent event) {
    pointsNotifier.addPoint(Point(
      event.localPosition,
      PointType.move,
    ));
},

Point里保存了一个PointType,如果是拖动类型(PointType.move),我们就把它和上一条线连起来

接下来准备Canvas画布:

class MyPainter extends CustomPainter {
  PointsNotifier _pointsNotifier;
  Paint _paint;

  MyPainter(this._pointsNotifier)
      : _paint = Paint(),
        super(repaint: _pointsNotifier) {
    _paint
      ..strokeWidth = 15
      ..blendMode = BlendMode.clear;
  }

  @override
  void paint(Canvas canvas, Size size) {
    Rect rect = Rect.fromCenter(
        center: Offset(size.width / 2, size.height / 2),
        width: size.width,
        height: size.height);

    canvas.saveLayer(rect, Paint());

    // 绘制蒙板
    canvas.drawRect(rect, Paint()..color = Colors.grey);

    final List<Point> points = _pointsNotifier.value;
    for (int i = 0; i < (points.length - 1); i++) {
      if (points[i + 1].type == PointType.move) {
        canvas.drawLine(
          points[i].offset,
          points[i + 1].offset,
          _paint,
        );
      }
    }

    canvas.restore();
  }

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

CustomPainter类中可以传入一个repaint来触发刷新,把PointsNotifier传进去即可,Paint的strokeWidth设置画笔粗细,blendMode设置为BlendMode.clear就是“橡皮擦”的效果

在void paint(Canvas canvas, Size size)方法中进行绘制,canvas.drawRect用来绘制蒙板,蒙板完成后,遍历pointsNotifier中保存的Point数组,完成橡皮擦线条绘制

下面这两条很重要:

canvas.saveLayer(rect, Paint());
canvas.restore();

如果blendMode设为BlendMode.clear,必须在绘制前调用saveLayer保存画布状态,绘制完成后restore恢复,否则“橡皮擦”不生效,线条颜色会变黑色

完整代码:

import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  double width = 200;
  double height = 100;

  PointsNotifier pointsNotifier = PointsNotifier();

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Listener(
        onPointerDown: (PointerDownEvent event) {
          pointsNotifier.addPoint(Point(
            event.localPosition,
            PointType.tap,
          ));
        },
        onPointerUp: (PointerUpEvent event) {
          pointsNotifier.addPoint(Point(
            event.localPosition,
            PointType.tap,
          ));
        },
        onPointerCancel: (PointerCancelEvent event) {
          pointsNotifier.addPoint(Point(
            event.localPosition,
            PointType.tap,
          ));
        },
        onPointerMove: (PointerMoveEvent event) {
          pointsNotifier.addPoint(Point(
            event.localPosition,
            PointType.move,
          ));
        },
        child: RepaintBoundary(
          child: CustomPaint(
            foregroundPainter: MyPainter(pointsNotifier),
            child: Container(
              width: width,
              height: height,
              color: Colors.redAccent,
              alignment: Alignment.center,
              child: Text(
                '再来一瓶',
                style: TextStyle(
                  fontSize: 28,
                  fontWeight: FontWeight.bold,
                  color: Colors.yellow,
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

enum PointType {
  tap,
  move,
}

class Point {
  Offset offset;
  PointType type;

  Point(this.offset, this.type);
}

class MyPainter extends CustomPainter {
  PointsNotifier _pointsNotifier;
  Paint _paint;

  MyPainter(this._pointsNotifier)
      : _paint = Paint(),
        super(repaint: _pointsNotifier) {
    _paint
      ..strokeWidth = 15
      ..blendMode = BlendMode.clear;
  }

  @override
  void paint(Canvas canvas, Size size) {
    Rect rect = Rect.fromCenter(
        center: Offset(size.width / 2, size.height / 2),
        width: size.width,
        height: size.height);

    canvas.saveLayer(rect, Paint());

    // 绘制蒙板
    canvas.drawRect(rect, Paint()..color = Colors.grey);

    final List<Point> points = _pointsNotifier.value;
    for (int i = 0; i < (points.length - 1); i++) {
      if (points[i + 1].type == PointType.move) {
        canvas.drawLine(
          points[i].offset,
          points[i + 1].offset,
          _paint,
        );
      }
    }

    canvas.restore();
  }

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

class PointsNotifier extends ValueNotifier<List<Point>> {
  PointsNotifier({List<Point>? points}) : super(points ?? <Point>[]);

  void addPoint(Point point) {
    value.add(point);
    notifyListeners();
  }
}

PS:期间碰到一个问题,如果画笔Paint设为圆头strokeCap = StrokeCap.round,疯狂绘制线条会越来越卡顿,没能找到解决办法,只能不设置strokeCap属性了

相关文章

  • Flutter canvas刮刮乐

    利用canvas画布给“刮奖区”上面盖一层蒙板,再利用Paint画笔的BlendMode.clear属性,把can...

  • canvas— —刮刮乐

    今天,结合上一篇文章的抽奖小游戏,用canvas来写一个小游戏——刮刮乐。首先,用canvas做一个画布,宽高各为...

  • canvas 刮刮乐

    今天我们来模拟刮刮乐效果 既然是使用Canvas来完成刮刮乐的效果,那么我们先来创建一个Canvas标签,并给它赋...

  • canvas刮刮乐

    在学习canvas 菜鸟一个 写的一个小demo HTML js

  • 使用Canvas实现刮刮乐效果

  • canvas-实现刮刮乐效果

    实现思路:0.设置canvas的大小和背景图片一样大1.获取canvas标签和上下文2.添加蒙版3.设置合成属性为...

  • 刮刮乐

  • 刮刮乐

    2007年3月3日,特别的日子。 为啥特别? 第一次坐飞机,青岛飞西安,提前4个小时就到机场了,在网上研究过攻略,...

  • 刮刮乐

    2014年11月3日 刮刮乐 今天杏子又在济南火车站候车了,这次她是故地重游,明显轻松了许多。 ...

  • 刮刮乐

    设置刮开后,显示的文字Label UILabel *label = [[UILabel alloc]initWit...

网友评论

      本文标题:Flutter canvas刮刮乐

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