使用颤动的绘图中的性能问题

时间:2018-05-02 10:16:55

标签: flutter

我正在使用gestuereDetector来检测偏移量,使用CustomePaint来绘制颤动中的偏移量。但绘图后绘图性能变慢,请帮我解决这个问题。

如何提高效率。我的代码如下

 Widget build(BuildContext context) {
    _currentPainter = new DrawPainting(_points);

    return new Container(
      child: new ConstrainedBox(
        constraints: const BoxConstraints.expand(),
        child: new GestureDetector(
          onPanUpdate: (DragUpdateDetails details) {
            setState(() {
              RenderBox referenceBox = context.findRenderObject();

              Offset localPosition =
              referenceBox.globalToLocal(details.globalPosition);
              _points = new List.from(_points)..add(localPosition);
            });
          },
          onPanEnd: (DragEndDetails details) =>_points.add(null),
          child: new CustomPaint(
            painter: _currentPainter,

          ),
        ),
      ),
    );
  }


class DrawPainting extends CustomPainter {
  List<Offset> points = [];
  Canvas _lastCanvas;
  Size _lastSize;
  DrawPainting(points){

    this.points = points;
  }

  void paint(Canvas canvas, Size size) {
    print({"the main paint is called .... ": {"size" : size}});
    _lastCanvas = canvas;
    _lastSize = size;
    Paint paint = new Paint()
      ..color = Colors.black
      ..strokeCap = StrokeCap.round
      ..strokeWidth = 8.0;


    for (int i = 0; i < points.length - 1; i++) {
      if (points[i] != null &&
          points[i + 1] != null &&
          (points[i].dx >= 0 &&
              points[i].dy >= 0 &&
              points[i].dx < size.width &&
              points[i].dy < size.height) &&
          (points[i + 1].dx >= 0 &&
              points[i + 1].dy >= 0 &&
              points[i + 1].dx < size.width &&
              points[i + 1].dy < size.height)){
        canvas.drawLine(points[i], points[i + 1], paint);
      }
    }
  }
  bool shouldRepaint(DrawPainting other) => other.points != points;
}

2 个答案:

答案 0 :(得分:2)

使用 drawPath ()解决了使用颤动的绘图应用程序中的性能问题,而不是对每个要更新的点使用 setState ,而使用 NotifyListener >()刷新会比setState效率更高。

答案 1 :(得分:0)

我写了一篇关于如何制作此功能的博客,希望对您有所帮助。

它描述了如何在绘制时摆脱奇怪的线条,以及如何实现擦除和撤消功能。此外,不使用 setState 而是使用 Bloc。

博客: https://ivanstajcer.medium.com/flutter-drawing-erasing-and-undo-with-custompainter-6d00fec2bbc2

总结:将所有线划分为对象,并为每条线存储一个Path,以及一个Offsets列表。然后通过调用 canvas.drawPath() 绘制路径(这比遍历所有偏移并在它们之间绘制更好)并在所有偏移中绘制一个圆。

希望这能解决您的问题。