简体   繁体   中英

LibGDX text not centered in smaller viewport

I'm working on a LibGDX game which uses a smaller viewport.

public static float BOX_SCALE = 10;
public static final float VIRTUAL_WIDTH = (int) (320 / BOX_SCALE);
public static final float VIRTUAL_HEIGHT = (int) (480 / BOX_SCALE);

float viewportHeight = MyConstants.Screen.VIRTUAL_HEIGHT;
float viewportWidth = MyConstants.Screen.VIRTUAL_HEIGHT * Gdx.graphics.getWidth() / Gdx.graphics.getHeight();


For example my viewport can have the size (32, 48). I use Scene2D for rendering. For some reason whenever i create a TextButton the text is never centered. This is the BitmapFont used for the button.

FreeTypeFontParameter fontParam = new FreeTypeFontParameter();
fontParam.size = 14;        

FreeTypeFontGenerator generator2 = new FreeTypeFontGenerator(Gdx.files.internal("data/font.ttf"));
labelFont = generator2.generateFont(fontParam);
labelFont.setScale(1f / BOX_SCALE); 
labelFont.setColor(Color.BLACK);

在此处输入图片说明


If i set the BOX_SCALE value to 1 then TextButton acts normal but i need for simulating the Box2D world. I guess i could create separate labels for each button and position them manually but I can't figure out why this is happening. Also interested if there is a cleaner solution.

By default, font positions are rounded off to nearest world game unit. This is based on an assumption that your font will render pixel perfect. In your case, you don't want a pixel perfect font, so call:

labelFont.setUseIntegerPositions(false);

Also, in your fontParam you should set it to use mipmaps, and set the minFilter to MipmapLinearNearest and the magFilter to Linear. That'll make it look better, since by default the filtering is set to Nearest/Nearest which looks bad if you aren't rendering pixel perfect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM