Libgdx添加Stage后font.draw()文本无法显示问题求助
font.draw() Not Showing After Adding a Stage in LibGDX Hey there! Let's break down why your text stopped showing up once you added a Stage—this is such a common gotcha for LibGDX newbies, so don't feel stuck! I've been there too, so let's walk through the most likely fixes:
1. SpriteBatch Conflict (The #1 Culprit)
Stage comes with its own SpriteBatch by default, and if you're using a separate SpriteBatch for your font, their drawing states can clash hard. Here's how to fix it:
If you're using separate Batches:
- Always wrap your font drawing in
sb.begin()andsb.end(), and make sure you callsb.end()beforestage.draw(). Stage will handle its own Batch's begin/end internally, so mixing unclosed Batches will mess up rendering. - Example:
// Draw font first sb.begin(); font.draw(sb, "My Text", 50, 50); sb.end(); // Critical to close before Stage draws // Now update and draw Stage stage.act(delta); stage.draw();
- Always wrap your font drawing in
If you want to share a Batch (more efficient):
- Pass your existing SpriteBatch to the Stage constructor:
Stage stage = new Stage(new ScreenViewport(), sb); - Now, don't call
sb.begin()beforestage.draw()—Stage will handle that for you. If you want to draw text after the Stage, re-open the Batch:stage.act(delta); stage.draw(); // Stage closes the Batch after drawing // Re-open to draw text sb.begin(); font.draw(sb, "Post-Stage Text", 50, 50); sb.end();
- Pass your existing SpriteBatch to the Stage constructor:
2. Your Text Is Getting Covered
Stage draws Actors in a layered order, and if you're drawing text before the Stage, it might be hidden behind an opaque Actor or the Stage's background. Try moving your font drawing after stage.draw() to see if it pops up. Also double-check your font's color—if you accidentally set font.setColor(new Color(1,1,1,0)), the text will be fully transparent!
3. Coordinate System Mismatch
Stage uses a ScreenViewport by default (origin at the bottom-left corner), while before adding Stage, you might have been using a different viewport. If your text is drawn at coordinates that are off-screen now, it won't show up. Test with a safe position like:
font.draw(sb, "Test Text", 20, Gdx.graphics.getHeight() - 20);
This places the text in the top-right corner, which is hard to miss if it's rendering correctly.
4. Batch State Got Modified
Stage can tweak Batch settings (like blend functions) when drawing certain Actors. If your text draws after the Stage, reset the Batch's blend function to default before drawing:
sb.begin(); sb.setBlendFunction(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA); // Restore default blending font.draw(sb, "Fixed Text", 50, 50); sb.end();
Try these steps one by one—chances are the first fix will resolve your issue. LibGDX's Batch/Stage interaction takes a little getting used to, but once you wrap your head around it, it's smooth sailing!
内容的提问来源于stack exchange,提问作者Ondřej Šerek

