Libgdx - how to add a background image to a scene?

I am learning libgdx but I am stuck at a point.

I added a button to my scene, now I want to add an image to the scene so that the image looks like the background image of a button. I want to say that the button should lie on the image. I was looking for textbooks but could not do it.

How can I do that? any help?

+8
java android game-engine libgdx scene2d
source share
3 answers

The only thing you need to do is draw background before you draw Button s.
There are several possible ways to do this:
- You can add the background as Image (a subclass of Actor ) to Stage and use the z-index to make sure it is drawn as a background.
- You can get Stage SpriteBatch ( stage.getBatch() ) and use one of the draw methods to paint the background before calling stage.draw()

You can also use another SpriteBatch , but I do not recommend it, since it is a rather "heavy" object, in which case it is simply not necessary.
I think that before calling stage.draw() you need to call spritebatch.end() , for the SpriteBatch that you used to draw background.

+12
source share

A small example:

 stage.act(Gdx.graphics.getDeltaTime()); stage.getBatch().begin(); stage.getBatch().draw(background, 0, 0, WORLD_WIDTH, WORLD_HEIGHT); stage.getBatch().end(); stage.draw(); 
+6
source share

Here is the code I used to emulate the status bars. I used the ProgressBar .

  stage = new Stage(); Texture bground = new Texture(Gdx.files.internal("pbBackground.png")); Table table = new Table(); table.setFillParent(true); stage.addActor(table); font = new BitmapFont(Gdx.files.internal("gamefonts.fnt")); font.getData().scale(.1f); skin = new Skin(); pixmap = new Pixmap(1, 1, Format.RGBA8888); pixmap.setColor(Color.WHITE); pixmap.fill(); skin.add("white", new Texture(pixmap)); LabelStyle lstyle = new LabelStyle(); lstyle.font=font; Label mylabel = new Label("HP", lstyle); mylabel.setColor(Color.RED); mylabel.setPosition(1, 6); table.addActor(mylabel); textureBar = new TextureRegionDrawable(new TextureRegion(new Texture(Gdx.files.internal("pb.png")))); barStyle = new ProgressBarStyle(skin.newDrawable("white", Color.DARK_GRAY), textureBar); barStyle.background = new TextureRegionDrawable(new TextureRegion(bground)); barStyle.knobBefore=barStyle.knob; bar = new ProgressBar(0, 10, 0.5f, false, barStyle); bar.setPosition(1, 1); bar.setValue(0); bar.setAnimateDuration(2); table.addActor(bar); 

This site can help you better understand progressbars. Also check out the docs for the ProgressBar .

-2
source share

All Articles