0

I'm currently developing a game. I'm using DP as measurement of all the objects, calculated back to PX via Metrics. The problem is, for example on my Nexus 7 tablet, all elements look good, they have the perfect sizes, but on my Nexus 4 they are simply too big - this is obviously because of the DP.

How can I achieve something like this:

The object is ALWAYS 1/5th of the screen's width?

Do I have to calculate the new width programmatically? If so, how would I do this? I would have to keep the density and the resolution of the display in mind, but I can't imagine how I could calculate this right now. Or is there any other way to make this happen?

BTW: I'm drawing on a Canvas, so I have to re-calculate all this into pixels.

This is what I currently use:

public int convertDpToPx(int dp) {
    DisplayMetrics displayMetrics = mActivity.getResources().getDisplayMetrics();
    return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, displayMetrics);
}
public int convertPxToDp(int px) {
    DisplayMetrics displayMetrics = mActivity.getResources().getDisplayMetrics();
    return (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_PX, px , displayMetrics);
}

And the Object #1 has for example a width of 100dp, but it takes a much bigger part of the screen on my 4.7 inch device than on my 7 inch tablet.

damian
  • 2,001
  • 20
  • 38

1 Answers1

1

Simple actually. Get the Activity's window via WindowManager and get the screen size/metrics. Then simply set the width of your View to be 1/5th of the Screen Width.

Here:

public class World extends Activity {

int screenWidth, screenHeight;

WindowManager w;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Point size = new Point();
    w = getWindowManager();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
        w.getDefaultDisplay().getSize(size);

        screenWidth = size.x;
        screenHeight = size.y;
    } else {
        Display d = w.getDefaultDisplay();
        screenWidth = d.getWidth();
        screenHeight = d.getHeight();
    }

    //here you can set the View's width to screenWidth/5
}

Hope this helps!

MattMatt
  • 905
  • 6
  • 19
  • Well, I kind of thought I would have to keep the screen's density and all that stuff in mind, but I guess you're right, it's as simple as that. Thank you – damian Aug 17 '13 at 17:17
  • Yep, easy as that :) You can also specify pixel units in an dimen.xml Check my answer here and see if that could help as well. http://stackoverflow.com/questions/18027054/use-density-independent-pixels-for-width-and-height-when-creating-a-bitmap/18028587#18028587 Happy coding! – MattMatt Aug 17 '13 at 17:20