0

What is the most effective way to put a generated image into the Flame.Images asset cache?

I can get the image from this method, but I don't know how to put the resulting Image object into the cache.

Future<Image> decodeImageFromPixels(
    Uint8List pixels,
    int width,
    int height, {
    bool runAsWeb = kIsWeb,
  })
spydon
  • 9,372
  • 6
  • 33
  • 63
  • Can you clarify a bit what it is that you want to do? Do you want to put your decoded image into the image cache so that you can fetch it with a name? – spydon Dec 09 '21 at 10:36
  • Yes, I want to generate an image from assets when uploading and save it in the cache – Vason GDesigner Dec 12 '21 at 11:42

1 Answers1

0

That does currently not work since the image cache only works on files. But you can quite easily create an image cache (just a map) in your game class, either as a static map or one that you can access through components that have the HasGameRef<YourGameClass mixin.

It would look like this:

class MyGame extends FlameGame {
  final generatedImages = <String, Image>{};

  @override
  Future<void> onLoad() async {
    await super.onLoad();
    final image = await Flame.images.decodeImageFromPixels(...);
    generatedImages['image name'] = image;
  }
}

Then in your component class where you want to use the image, if it is a SpriteComponent for example:

class MyComponent extends Component with HasGameRef<MyGame> {
  @override
  Future<void> onLoad() async {
    await super.onLoad();
    sprite = Sprite(gameRef.generatedImages['image name']);
  }
}

or if you are not extending a component, but still using a SpriteComponent you can do this wherever you want that component (that has access to the gameRef):

final spriteComponent = SpriteComponent.fromImage(gameRef.generatedImages['image name']);

Note you could also make the generatedImages map static and just access it with MyGame.generatedImages['image name']; without having a gameRef.

spydon
  • 9,372
  • 6
  • 33
  • 63