Reputation: 95
I tried everything I could, but my libgdx application won't scale down on android 2.2. It displays a full image of 640x480 on a screen of only 480x320. Here's the code I got so far;
private static final int VIRTUAL_WIDTH = 640;
private static final int VIRTUAL_HEIGHT = 480;
private static final float ASPECT_RATIO = (float)VIRTUAL_WIDTH/(float)VIRTUAL_HEIGHT;
public static Texture BMP_BACKGROUND;
public static Rectangle viewport;
public static OrthographicCamera camera;
public static SpriteBatch batch;
public void create()
{
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
BMP_BACKGROUND = new Texture(Gdx.files.internal("data/bmpSpaceBackground.png"));
BMP_BACKGROUND.setFilter(TextureFilter.Nearest, TextureFilter.Nearest);
batch = new SpriteBatch();
camera = new OrthographicCamera(VIRTUAL_WIDTH, VIRTUAL_HEIGHT);
}
@Override
public void dispose()
{
batch.dispose();
BMP_BACKGROUND.dispose();
}
@Override
public void render()
{
camera.update();
camera.apply(Gdx.gl10);
// set viewport
Gdx.gl.glViewport((int) viewport.x, (int) viewport.y,
(int) viewport.width, (int) viewport.height);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
batch.draw(BMP_BACKGROUND, 0, 0);
Game.run();
}
public void resize(int width, int height)
{
float aspectRatio = (float)width/(float)height;
float scale = 1f;
Vector2 crop = new Vector2(0f, 0f);
if(aspectRatio > ASPECT_RATIO)
{
scale = (float)height/(float)VIRTUAL_HEIGHT;
crop.x = (width - VIRTUAL_WIDTH*scale)/2f;
}
else if(aspectRatio < ASPECT_RATIO)
{
scale = (float)width/(float)VIRTUAL_WIDTH;
crop.y = (height - VIRTUAL_HEIGHT*scale)/2f;
}
else
{
scale = (float)width/(float)VIRTUAL_WIDTH;
}
float w = (float)VIRTUAL_WIDTH*scale;
float h = (float)VIRTUAL_HEIGHT*scale;
viewport = new Rectangle((int)crop.x, (int)crop.y, (int)w, (int)h);
}
Anyone can tell me what I'm doing wrong?
Upvotes: 0
Views: 1140
Reputation: 6221
Try this
public void resize(int width, int height)
{
cam.viewportHeight = height; //set the viewport
cam.viewportWidth = width;
if (Config.VIRTUAL_VIEW_WIDTH / cam.viewportWidth < Config.VIRTUAL_VIEW_HEIGHT
/ cam.viewportHeight) {
//sett the right zoom direct
cam.zoom = Config.VIRTUAL_VIEW_HEIGHT / cam.viewportHeight;
} else {
//sett the right zoom direct
cam.zoom = Config.VIRTUAL_VIEW_WIDTH / cam.viewportWidth;
}
cam.update();
}
This does work and i can work with the virutal resolution. But dont forget to set the camera of your stage you are using! Else it does have no effect!
stage.setCamera(camera)
.
if you have done that you can work with the virtual resolution inside of your stage.
regards
Your code is 1:1 from an example online.
Upvotes: 2