【问题标题】:How can I replace Flutter widgets with canvas and vice versa?如何用画布替换 Flutter 小部件,反之亦然?
【发布时间】:2017-11-29 23:26:35
【问题描述】:

我正在使用 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,类似于 Widget 的工作方式。

class _CustomBinder extends BindingBase with ServicesBinding {}

这对游戏很有用,但我希望在主菜单、设置页面等中使用真正的颤振小部件。

有没有办法在这两个上下文之间交换?

为了提供我在寻找什么的想法,我希望存在这两个功能:

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

【问题讨论】:

  • Canvas 甚至不是来自 Flutter。很可能有一种方法,但不足以在stackoverflow中回答。 Flutter 的替代方案是CustomPaint
  • 这解释了一些事情。不幸的是,我放弃了我正在使用的当前库(类项目)并迅速达到同等水平。
  • Flutter Flame 还不到一个月。您的项目不能那么大到无法返回的地步吗?
  • 不,不,它不是很大,但我还有其他事情要做。这不是一个巨大的优先项目。今晚我将尝试尝试github.com/vlidholt/flutter_sprites

标签: flutter flame


【解决方案1】:

在较新版本的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

【讨论】:

    猜你喜欢
    • 2019-03-17
    • 2019-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多