首页 文章

Flutter - 如何用画布替换Flutter小部件,反之亦然

提问于
浏览
1

我有一个相当奇怪的问题我使用Flutter Flame进行2D游戏 . 该库使用画布,如下所示:

start() {
  var previous = Duration.ZERO;

  window.onBeginFrame = (now) {
    var recorder = new PictureRecorder();
    var canvas = new Canvas(
        recorder,
        new Rect.fromLTWH(
            0.0, 0.0, window.physicalSize.width, window.physicalSize.height));

    Duration delta = now - previous;
    if (previous == Duration.ZERO) {
      delta = Duration.ZERO;
    }
    previous = now;

    var t = delta.inMicroseconds / Duration.MICROSECONDS_PER_SECOND;

    update(t);
    render(canvas);

    var deviceTransform = new Float64List(16)
      ..[0] = window.devicePixelRatio
      ..[5] = window.devicePixelRatio
      ..[10] = 1.0
      ..[15] = 1.0;

    var builder = new SceneBuilder()
      ..pushTransform(deviceTransform)
      ..addPicture(Offset.zero, recorder.endRecording())
      ..pop();

    window.render(builder.build());
    window.scheduleFrame();
  };

  window.scheduleFrame();
}

值得注意的是,Flutter Flame使用自定义BindingBase,类似于Widgets的工作方式 .

class _CustomBinder extends BindingBase with ServicesBinding {}

这对游戏非常有用,但我希望在主菜单,设置页面等中使用真正的颤动小部件 .

有没有办法在这两种情境之间进行交换?

为了提供我正在寻找的东西,我希望它存在这两个功能:

loadHomeScreen(); // replaces the canvas, if any, with Flutter widgets
loadCanvasScene(); // replaces the Flutter widgets with the canvas

1 回答

  • 2

    在较新版本的Flame(0.8.x)中,游戏成为常规小部件,因此支持具有用于菜单和设置的常规小部件的应用程序 .

    从常规应用开始,在您的一种构建方法中,添加游戏实现的小部件:

    class MyGame extends BaseGame {
      // your game here
    }
    
    // in your game screen class
    
    final MyGame game = new MyGame();
    
    @override
    Widget build(BuildContext context) {
      return game.widget;
    }
    

    有关更深入的示例,请检查this complete game,使用最新版本的Flame构建 . 您正在寻找的特定代码,在游戏和应用之间切换是here .

相关问题