Sunday, April 21, 2019

android - How do I support variable screen ratios using AndEngine?


When displaying a background, AndEngine produces black bars above the image on certain devices. How do I support variable screen ratios for different devices using AndEngine?



Answer



I believe what you're asking is how to get rid of letterboxing, like this:


enter image description here


By default, AndEngine assumes you want some fixed aspect ratio. It then uses letterboxing to handle devices with different display aspect ratios then what you're providing. The advantage is you have certainty about your layout.


There's more than one approach to get rid of them, but here's what I do. The following code takes a fixed height (in this case 320) and adjusts the width based on the aspect ratio of the device.


//Pick some value for your height.
float cameraHeight = 320;


//Get the display metrics object.
final DisplayMetrics displayMetrics = new DisplayMetrics();

//Populate it with data about your display.
this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

//Calculate the aspect ratio ofthe device.
float aspectRatio = (float) displayMetrics.widthPixels / (float) displayMetrics.heightPixels;


//Multiply the aspect ratio by the fixed height.
float cameraWidth = Math.round(aspectRatio * CAMERA_HEIGHT);

//Create the camera using those values.
this.mCamera = new Camera(0, 0, cameraWidth, cameraHeight);

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...