Handling different screen resolutions for background images in Android - android

My Android app (a text-based game) uses background images a lot in order to provide a better visual ambiance. For example, if the action in the game takes you into a tavern, then you get a background image of a tavern in the game. This is a vast improvement, graphically, over the boring black background that you would otherwise get.
It is also a problem, however, since android:background always stretches to the dimensions of the screen. The result is that the background images look very bad if the player switches between portrait and landscape mode. And to make matters worse, many devices have very different aspect ratios (e.g., 320x480 mdpi, 480x800 hdpi, and 480x852 hdpi) and even more variations are coming.
How do others solve this problem? Having individual images for the main resolutions/orientations is not an option for me, as this would result in the apk growing too large.

The first step is to get the screen height and width of the device itself, then stretch/shrink or pad your bitmap as needed. This SO answer has source that should help, copied below. Props to Josef for original answer.
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
Here's generic source on getting the orientation.
int orientation = display.getOrientation();
or some more involved source from here (a little messy but looks correct).
public int getscrOrientation()
{
Display getOrient = getWindowManager().getDefaultDisplay();
int orientation = getOrient.getOrientation();
// Sometimes you may get undefined orientation Value is 0
// simple logic solves the problem compare the screen
// X,Y Co-ordinates and determine the Orientation in such cases
if(orientation==Configuration.ORIENTATION_UNDEFINED){
Configuration config = getResources().getConfiguration();
orientation = config.orientation;
if(orientation==Configuration.ORIENTATION_UNDEFINED){
//if height and widht of screen are equal then
// it is square orientation
if(getOrient.getWidth()==getOrient.getHeight()){
orientation = Configuration.ORIENTATION_SQUARE;
}else{ //if widht is less than height than it is portrait
if(getOrient.getWidth() < getOrient.getHeight()){
orientation = Configuration.ORIENTATION_PORTRAIT;
}else{ // if it is not any of the above it will defineitly be landscape
orientation = Configuration.ORIENTATION_LANDSCAPE;
}
}
}
}
return orientation; // return value 1 is portrait and 2 is Landscape Mode
}

I would suggest you get the width and height of your current view. Right now I am not sure what functions will give you these values but I am sure it is possible. With that you can then calculate an aspect ratio. I'd make the images something like 1000x1000 and just show a certain part of the image, so that the aspect ratio will not be wrong.
I have the same problem with the camera. So my solution was to pick one of the two values, width or height, as fixed, and calculate the correct other value according to the aspect ratio. I'm not sure if there are functions already to just show a part of the image, but I am sure you could write something to copy just a part of the image and show that part.
The drawback is of course that you will be showing just a part of the background. Since the general aspect ratio of the phones is however somewhere between 1:1.3 and 1:1.8 I guess it wouldn't be a too big problem. I for one would rather see the part of an image in the correct way, than looking at an ugly stretched image.

Maybe you could create your background images as NinePatch images so that you are in better control of how it stretches?
Otherwise, you can just prevent your images from stretching (or at least keep the correct aspect ratio) by setting the scaleType attribute e.g. android:scaleType="center".

Related

Restricting an app's screen size based on a phone's resolution

I am developing an application in android studio which is displayed correctly on 1080x1920 phones(and lower) but for phones like mine(s8) the app gets messed up and i can't find a way to fix the app's ui for every screen size. So, i was wondering if there is a way to restrict the app's screen size to 1080x1920(with let's say black bars at the top & bottom of the screen) even if a phone's dimensions are bigger than that(this is automatically done in games that are not compatible with s8). Do you guys know a way of achieving this effect?
It's possible, you can set your parent View to exact size given the aspect ratio you want (1080x1920 scales down to 9x16). For this you'd have to programmatically call the View (or create it in code) and set width and height in pixels with LayoutParams:
yourView.setLayoutParams(new LayoutParams(width, height));
for the weight and height you'd want the actual screen dimensions, which you can get from the WindowManager:
WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
Point point = new Point();
display.getSize(point);
int x = point.x;
int y = point.y;
Here you get the x and y, which hold your actual screen size (in pixels). Then, you decide on which one should be reduced (in order to maintain 9x16 aspect ratio) and set your parent View's LayoutParams as mentioned above.
Finally, your set your content View as your parent View:
setContentView(yourView);
That's about it. Hope that helps.
EDIT: Since you've mentioned games, I can tell you that there (if your use Android SDK) you have your SurfaceView as a parent View, the procedure is same.

how to get android screen size programmatically, once and for all?

How can I find out my screen size programmatically,
in the units used by touch events
and View measurement/layout?
In other words, I want the coordinates
of the bottom-right corner of the screen,
in the coordinate system used by touch events'
getRawX()/getRawY() and View.getLocationOnScreen().
I'm hesitant to call the desired event/view units "pixels"
since evidently there are several notions of "pixels"
on my phone in various modes,
and they're not adding up to a consistent story.
I see this has been asked and answered a lot
on stackoverflow and elsewhere,
but none of the answers actually work on my phone
(droid 4, android 4.1.2) in all modes:
Can I find out width of screen programmatically in android app?
How do I get the ScreenSize programmatically in android
Android set View visibility programmatically based on screen size
How do I get the height of the screen in Android?
Get the screen height in Android
https://groups.google.com/forum/#!topic/android-developers/IpxnfvDFrpc
http://shuklaxyz.blogspot.com/2012/02/how-to-programmatically-figure-out.html
http://coderock.net/how-to-determine-screen-resolution-programmatically/
http://www.codeproject.com/Tips/313848/Get-actual-screen-size-for-the-application-layout
Android and setting width and height programmatically in dp units
http://www.simplecodestuffs.com/how-to-get-screen-dimensions-programmatically-in-android/
http://www.androidsnippets.com/get-size-and-orientation-of-the-screen
http://grokbase.com/t/gg/android-developers/127aatfqb6/how-to-determine-screen-resolution-programmatically
(wow!)
This is for library code that needs to work
regardless of whether the app is in "screen compatibility mode"
(i.e. targetSdkVersion<=10 in the manifest) or not,
and I also don't want to make any assumptions
about the position, size, or existence of the status bar
or any other similar screen decorations.
Here are the facts:
my phone (a droid 4 running android 4.1.2)
has 540x960 physical pixels,
i.e. little colored glowing dots.
the size of the screen in the desired units,
from looking at touch events and View measurements, is
360x640 when the app is in screen compat mode,
540x960 when the app is not in screen compat mode.
These are the numbers I need to find programmatically,
without mucking with touch events or Views to find them,
but I'm having extreme difficulty finding any API
that will return these numbers.
Display and DisplayMetrics objects obtained
in various ways all claim the screen size
is 540x960 "pixels"
(whether in screen compat mode or not).
To be specific, the following all say 540x960 all the time:
DisplayMetrics.{width,height}Pixels,
Display.getSize(),
Display.getRealSize(),
Display.get{Width,Height}(),
Configuration objects obtained in various ways
all say screen{Width,Height}Dp = 360x614
(whether in screen compat mode or not).
I don't believe that represents the whole screen,
since the aspect ratio is wrong.
(I think it's the whole screen
minus the status bar; I need the whole screen.)
I think it's safe to say that the whole screen is 360x640 dp,
though I don't know any API that returns that 640.
DisplayMetrics obtained in various ways
say the "density" is
1.0f when in screen compat mode,
1.5f when not in screen compat mode.
The activity's
getWindow().getAttributes().{width,height}
isn't helpful since it typically contains MATCH_PARENT
rather than actual sizes.
But I can apparently get the desired answer from an activity's
getWindow().getDecorView().getMeasured{Width,Height}()
(which is actually surprising since
the activity's window's decorView
doesn't look like it's taking up the whole screen;
it looks like it's taking up the screen minus the status bar).
But I don't want to rely on this because if the window ever gets resized
(soft keyboard appearing? someone calling window.setAttributes()?
or maybe I'm not in an Activity at all),
this is clearly going to be all wrong.
I understand the following formula is supposed to hold:
pixels = dp * density
That seems to agree with all the reported numbers ((3),(4),(5) above)
when not in screen compatibility mode:
540x960 = 360x640 * 1.5
But in screen compatibility mode it doesn't add up:
540x960 != 360x640 * 1
So, something is awry.
The simplest explanation, I think,
is that the methods listed in (3) above
are simply giving the wrong answer for "pixels" when
in screen compat mode-- that is, they were intended
to return 360x640 "pixels" but they are wrongly returning 540x960 instead.
But there may be other ways of looking at it.
In any case, getting the desired numbers regardless of mode,
from the above puzzle pieces, is certainly a tricky puzzle.
I have found a way that seems to work on my phone in both modes,
but it is extremely circuitous,
and it relies on two assumptions that still seem rather shaky
(as described in the code comments below).
Here is my recipe:
/** get screen size in "pixels", i.e. touchevent/view units.
* on my droid 4, this is 360x640 or 540x960
* depending on whether the app is in screen compatibility mode
* (i.e. targetSdkVersion<=10 in the manifest) or not. */
public void getScreenSizePixels(int widthHeightInPixels[/*2*/])
{
Resources resources = getResources();
Configuration config = resources.getConfiguration();
DisplayMetrics dm = resources.getDisplayMetrics();
// Note, screenHeightDp isn't reliable
// (it seems to be too small by the height of the status bar),
// but we assume screenWidthDp is reliable.
// Note also, dm.widthPixels,dm.heightPixels aren't reliably pixels
// (they get confused when in screen compatibility mode, it seems),
// but we assume their ratio is correct.
double screenWidthInPixels = (double)config.screenWidthDp * dm.density;
double screenHeightInPixels = screenWidthInPixels * dm.heightPixels / dm.widthPixels;
widthHeightInPixels[0] = (int)(screenWidthInPixels + .5);
widthHeightInPixels[1] = (int)(screenHeightInPixels + .5);
}
Is there any better/cleaner way
to find the size of the screen??
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
Now you can measure your screen size in pixel which is a better measurement unit than centimeter because all the buttons ,textviews etc.. are measured in this unit. That what I use normally
By using the DisplayMetrics you can get height and width of the screen of any device. Note that width and height are sensitive to rotation.
here is the code.
DisplayMetrics metrics;
int width = 0, height = 0;
In your onCreate Method
metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
height = Math.min(metrics.widthPixels, metrics.heightPixels); //height
width = Math.max(metrics.widthPixels, metrics.heightPixels); //width
Try this.
In your #6, you note that the DecorView seems to provide what you want, but you don't think it is realiable. I believe that is as close as you can come. According to the documentation for Window.getDecorView:
Retrieve the top-level window decor view (containing the standard window frame/decorations and the client's content inside of that), which can be added as a window to the window manager.
The status bar is part of the window decoration mentioned there. Software keyboards and other overlays will receive their own window, so they shouldn't interfere with the relevant values. It is correct that isn't precisely the display metrics, but if your application is full screen it should always be the full screen size filtered through the compatibility translator. Other applications won't have access to your application's Window, so there is no need to worry about some other app changing the attributes while you aren't looking.
Hope that helps.
I should put this as a comment but I don't have the rep for that.
This may not be a totally correct answer but I got my dimensions when I switched the height and width in the DisplayMetrics method.
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
width = metrics.heightPixels;
height = metrics.widthPixels;
as I said this may not be correct but I don't know why but it worked for me.
If you are using api level 17 or higher check out getRealMetrics and getRealSize in Display
For api level 14,15 & 16 look here
I've used Pythagoras theorem to find the diagonal size of Android phone/tablet screen, same principal can be applied to iPhone or Blackberry screen.
DisplayMetrics met = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(met);// get display metrics object
String strSize =
new DecimalFormat("##.##").format(Math.sqrt(((met.widthPixels / met.xdpi) *
(met.widthPixels / met.xdpi)) +
((met.heightPixels / met.ydpi) * (met.heightPixels / met.ydpi))));
// using Dots per inches with width and height
Pythagoras must have been a genios, he knew smart phone programming so many years ago :p
I use the below method to get the width of the device :
public static int getDeviceWidth(Context context){
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
int width=display.getWidth();
return width;
}
I think this function will help you to simply get the width and height of your android screen size. The function returns the width and height as an array of integers as shown below
private int[] getScreenSIze(){
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int h = displaymetrics.heightPixels;
int w = displaymetrics.widthPixels;
int[] size={w,h};
return size;
}
and on your create method output your width and height as shown below
int[] screenSize= getScreenSIze();
int width=screenSize[0];
int height=screenSize[1];
screenSizes.setText("Phone Screen sizes \n\n width = "+width+" \n Height = "+height);
Download source code and test it on your android studio
This works for me:
int width = Resources.getSystem().getDisplayMetrics().widthPixels;
int height = Resources.getSystem().getDisplayMetrics().heightPixels;
I used this to update width of my items in a horizontal recycler view.(according to my requirement)
Hope it helps someone!
For this solution in Kotlin, try this:
private fun yourFunction(){
val metrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(metrics)
val width = metrics.widthPixels
val height = metrics.heightPixels
}

Use alternative layout when there's not enough space

I have a RelativeLayout that has a number of controls in it. On some screens, there might not be enough room for this layout as well as the other screen elements. In this case, I'd like to use an alternate layout that excludes some controls and has less padding.
How can I implement this in a performant manner? The smaller layout should only be loaded if the larger layout definitely won't fit. I don't want to use the various screen size qualifiers because whether the layout will fit is a function of the width and height of the screen and the additional visible controls and that seems like it will get too complicated.
I Personally think you should use the new screen size qualifiers. It's how Android is designed and I think you should follow those rules. It will very probably also make the whole development process a lot easier!
But if you insist on doing it yourself, the only way I can think of to "hardcode" it, would be something like this:
Step 1: obtain the screen size
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
or if you're targeting a lower API level:
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth(); // deprecated
int height = display.getHeight(); // deprecated
Step 2: pick an alternative layout depending on the screen size
if(width < value_x_small && height < value_y_small){
setContentView(R.layout.main_small);
} else if(width > value_x_small && height > value_y_small){
setContentView(R.layout.main_large);
} else {
setContentView(R.layout.main_larged);
}
This code allows you to select your own resources depending on the screen size in px. Its probably better to convert the px values to DP (DPI) and use those to make your decisions.You might also want to add a check on the current screen orientation.
You can implement your controls as separate Fragments and position them depending on screen size. Here is more info about Fragments and their Design Philosophy .

Image view resizing

So I have been facing this problem for a while and still I cant find solution for it. Hopefully you guys can give me a hand in this. I have a cards game that a player can see his cards like any other cards game.
The problem is that a lot of people complained that cards are too small.When I run it on my devicr (galaxy s2) the cards size are good. By chance someone sent me a screenshot from his HTC and the cards are indeed smaller than What I have.
Please note that I have this 3 different density folders and my Images view are set at wrap content.
I Have 2 solutions in mind and I appreciate if you can help further
1) instead of wrap content, I user a predefined width for each screen size (not density).This will garaunter a specifc size (space it occupies)on large screens for example
2) Make the imageview size relative to the width of the screen.I dont know how to do it so any pointers are appreciated.
3) any suggestions?
please help a programmer stuck in this delemma
You can use DesplayMetrics to get the dimensions of the device at run time and use the width and height you get.
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int width = metrics.widthPixels;
int height = metrics.heightPixels;
ImageView iv = (ImageView)findViewById(R.id.yourImageViewId);
iv.setWidth(width);
iv.setHeight(height * 2/3);
or something like that. this way you will never get such issues.
Do you have images in different sizes for different densities? Which scale type are you using for ImageViews?
You can create different layouts for densities but I would start with experimenting with scale types - http://developer.android.com/reference/android/widget/ImageView.ScaleType.html

How to calculate the Resolution According to some specific resolution?

In My Application i have One button like this :
The Resolution of that button is 192x32. And when i put this button in to drawable-mdpi, it seems good to layout. Now for other screen resolution for multiple screen support which size of button i have to make to see the Good Layout Design according to other Devices screen ?
I mean for drawable-ldpi and drawable-hdpi, which resolution i have to make for this button ? How to do Such calculation for to make this button size to fit for all the screen size ?
Please help me for this.
Thanks.
No need to create multiple buttons for multiple screen support.
Instead create a single button and set the width and height at run time.This is achieved by getting the display width and height. Use the bellow code to get the display H & W values.
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
based in the above values set the button width and height at runtime.
Example:
Button bt=(Button)findViewById(R.id.button);
bt.setWidth(width);//screen width(fill_parent)
bt.setHeight(height/6);//1/6 of the screen height
The above code set the button width to screen(display) width size and height to 1/6 of the screen.
There is much information on this subject on the android developers website. In particular, there is a list of the various dpi levels and what range of DPIs that they correspond to.
Also, Rather than providing different images for different resolutions, you could make the image a nine-patch, and have it auto-magically expand to fit the button. Although if you want to keep the highlighting in the background proportional, it might be somewhat difficult to make it expand vertically.

Categories

Resources