是否在不更新状态/重建小部件的情况下重新绘制CustomPaint



我想了解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;
}
}

Thx到@pskink对于注释中的提示,这里是工作解决方案,在调用MyCustomPainter类的构造函数时使用ChangeNotificationer。

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;
}
}

相关内容

  • 没有找到相关文章