0

In the pure Java version, calling width() or height() on Image or on ImageLayer works. But with HTML5 backend I get zero if I call it too early.

Image image = assets().getImage("images/myimage.png"); 
ImageLayer layer = graphics().createImageLayer(image);
float w1 = image.width(); 
float w2 = layer.width();

I tried right after the getImage() in the initialization code of the game and also from the paint() method, the first time paint() is called. But I always get zero with the HTML5 backend (Chrome, MacOs). However, if I call width() after the second call to the paint() method I get the correct width. So it seems that with the HTML5 backend the semantics is different: the width() method returns the correct width of an image / layer after it has been rendered a first time.

Is my interpretation correct and how to get the size before rendering?

fredstroup
  • 60
  • 8

2 Answers2

1

The Asset Watcher is working well. Alternatively, you can add a callback to your image. When the image is loaded a 'done' function is called.

Taken from pea.java:

// Add a callback for when the image loads.
// This is necessary because we can't use the width/height (to center the
// image) until after the image has been loaded
image.addCallback(new ResourceCallback<Image>() {
  @Override
  public void done(Image image) {
    layer.setOrigin(image.width() / 2f, image.height() / 2f);
    layer.setTranslation(x, y);
    peaLayer.add(layer);
  }


  @Override
  public void error(Throwable err) {
    log().error("Error loading image!", err);
  }
});
Rock Solid
  • 91
  • 1
  • 4
0

Have you tried using the AssetWatcher? It looks like those first width calls are outracing the document's ability to load the image.

Here's a simple example of the AssetWatcher in action:

And here's an implementation of AssetWatcher from the PlayN Showcase sample:

klenwell
  • 6,978
  • 4
  • 45
  • 84