0

我试图了解 customPaint 的工作原理,我想在画布上逐帧绘制自定义动画。

我可以通过每 1/60 秒重新绘制小部件来使其工作,但这听起来效率不高。我想每 1/60 秒渲染一次 CustomPainter,但这似乎不起作用。非常感谢任何注释或评论,以帮助我理解我应该如何实现这一目标。谢谢。

这是我正在使用的代码:

class CustomAnimatedWidgetState extends State<CustomAnimatedWidget> {

  CustomPaint _paint=null;
  MyCustomPainter _painter=null;

  double animationFrame=0;

  void tick() {   
    //called eery 1/60 seconds 
    animationFrame+=1/60;
    _painter.setAnimationFrame(animationFrame);
    _paint.METHOD_I_DONT_KNOW_TO_FORCE_REDRAW();
    // I want to avoid setState({animationFrame+=1/60;}); which works actually, but that doesn't sound very efficient to redraw the widget every 1/60 seconds, unless it's the right way to do it ?
  }


  @override
  Widget build(BuildContext context) {
    //developer.log('axis='+axis.toString(), name: 'DEBUG');


    _painter=MyCustomPainter();
    _painter.setAnimationFrame(animationFrame);

    _paint=CustomPaint(
      painter: _painter,
      child: Container(),
    );

    return _paint;
  }
}
4

1 回答 1

1

感谢@pskink 评论中的提示,这是工作解决方案,在调用 MyCustomPainter 类的构造函数时使用 ChangeNotifier。

class CustomAnimatedWidgetState extends State<CustomAnimatedWidget> {

  CustomPaint _paint=null;
  MyCustomPainter _painter=null;
  ChangeNotifier _repaint=ChangeNotifier();

  double animationFrame=0;

  void tick() {   
    //called eery 1/60 seconds 
    animationFrame+=1/60;
    _painter.setAnimationFrame(animationFrame);
    _repaint.notifyListeners();
  }


  @override
  Widget build(BuildContext context) {
    _painter=MyCustomPainter(repaint:_repaint);
    _painter.setAnimationFrame(animationFrame);

    _paint=CustomPaint(
      painter: _painter,
      child: Container(),
    );

    return _paint;
  }
}
于 2020-04-23T10:31:28.737 回答