Flutter Flame Background image full screen

531 Views Asked by At

I'm using the Tick Tack Toe app sample and modified the Play session screen to use a Flame Game widget. I'm trying to set a full screen background image (windows) that will resize when the window resizes. The code below works great if I remove the Game widget and replace with a Container but when using the Game widget the background will not resize. Is there a better way of doing this?

 return Scaffold(
    body: Container(
        width:MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage("assets/images/background1.png"),
            fit: BoxFit.fill,
          ),
        ),
        // Replace the GameScreen with Container and it works as desired
        child: GameScreen(level)));

}

2

There are 2 best solutions below

1
On BEST ANSWER

You can try this code, hope it helps:

class Background extends SpriteComponent with HasGameRef<FlappyBirdGame> {
  Background();

  @override
  Future<void> onLoad() async {
    final background = await Flame.images.load("Insert your background here");
    size = gameRef.size;
    sprite = Sprite(background);
  }
}

Here is "YourGame" class:

class YourGame extends FlameGame with TapDetector, HasCollisionDetection {
  YourGame();

  @override
  Future<void> onLoad() async {
    addAll([
      Background(),
    ]);
  }

  @override
  void onTap() {
  }

  @override
  void update(double dt) {
    super.update(dt);
  }
}

And in main.dart file:

Future<void> main() async {
  SystemChrome.setSystemUIOverlayStyle(
      const SystemUiOverlayStyle(statusBarColor: Colors.transparent));
  WidgetsFlutterBinding.ensureInitialized();
  await Flame.device.fullScreen();
  final game = YourGame();
  runApp(
    GameWidget(
      game: game,
      ...
    ),
  );
}
1
On

If you use the same full screen background throughout your game, you can try to set the background image inside the backgroundBuilder.

Future<void> main() async {
  SystemChrome.setSystemUIOverlayStyle(
      const SystemUiOverlayStyle(statusBarColor: Colors.transparent));
  WidgetsFlutterBinding.ensureInitialized();
  await Flame.device.fullScreen();

  final game = YourGame();

  runApp(
    GameWidget(
      game: game,
      // Set full screen background.
      backgroundBuilder: (context) => Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
              image: AssetImage("Insert your background here"),
              fit: BoxFit.cover),
        ),
      ),
    ),
  );
}

It will resized accordingly to your windows screen. Hope that helps.