【问题标题】:Flutter custom painter classFlutter 自定义画家类
【发布时间】:2018-10-23 08:14:35
【问题描述】:

flutter中自定义painter类的shouldRepaint方法如何工作? 我已经阅读了documentation,但我不明白如何以及何时向我们发送它。

【问题讨论】:

    标签: flutter flutter-animation


    【解决方案1】:

    这是一种提示框架是否需要调用CustomPainterpaint 方法的方法。

    假设您有一个带有颜色的小部件。

    class SomeWidget extends StatelessWidget {
      final Color color;
    
      SomeWidget(this.color);
    
      @override
      Widget build(BuildContext context) {
        return new CustomPaint(
          painter: new MyPainter(color),
        );
      }
    }
    

    这个 Widget 可以被框架多次重建,但只要传递给构造函数的 Color 没有改变,并且 CustomPainter 不依赖于其他任何东西,那么重新绘制 CustomPaint 就没有意义了。当颜色发生变化时,我们想告诉框架它应该调用paint。

    因此,如果颜色已更改,CustomPainter 可以通过返回 true 来提示框架。

    class MyPainter extends CustomPainter {
      final Color color;
    
      MyPainter(this.color);
    
      @override
      void paint(Canvas canvas, Size size) {
        // this paint function uses color
        // as long as color is the same there's no point painting again
        // so shouldRepaint only returns true if the color has changed
      }
    
      @override
      bool shouldRepaint(MyPainter oldDelegate) => color != oldDelegate.color;
    }
    

    【讨论】:

    • 而旧的委托参数是小部件在重建之前使用的 MyPainter 对象?
    • 是的,框架将上次调用paint时的MyPainter对象交还给你,并说“这是不同的吗,因为如果是这样,我现在会再次调用paint,这样你就可以绘画了有了这个新的、不同的 MyPainter"
    • 如果我不想重新绘制我的 CustomPainter,我该怎么办? @override bool shouldRepaint(MyPainter oldDelegate) => false;
    猜你喜欢
    • 2022-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    • 1970-01-01
    • 1970-01-01
    • 2019-02-23
    相关资源
    最近更新 更多