问题
I am learning libgdx but i am stuck at a point..
I have added a button in my stage , now i want to add a image in the stage so that the image looks as the background image to the button.i mean to say that the button should lie on the image. I have been looking tutorials but not been able to do that.
How can it be done? any help?
回答1:
The only thing you need to do is to draw
the background, before drawing the Button
s.
There are a few possible ways to do that:
- You can add the background as an Image
(subclass of Actor
) to the Stage
and use the z-index
to make sure it is drawn as a background.
- You can get the Stage
s SpriteBatch
(stage.getBatch()
) and use one of its draw
methods to draw the background, before calling stage.draw()
You could also use another SpriteBatch
, but i don't recommend it, as it is a pretty "heavy" object and it is just not neccessaty in this case.
I guess, before calling stage.draw()
you need to call spritebatch.end()
, for the SpriteBatch
you used to draw
the background.
回答2:
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();
回答3:
Here is some code I used to mimic a health bar. I used a 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 website may help you understand progressbars better. Also look at the docs for ProgressBar.
来源:https://stackoverflow.com/questions/22536755/libgdx-how-to-add-background-image-in-stage