How to use DPI scaling factor (float) to set margi

2019-06-05 09:24发布

问题:

My Android app looks great at 480x800 pixels resolution but it breaks at LDPI screen with 240x400 pixels. I know I can get scaling factor of screen in activity using getResources().getDisplayMetrics().density which would give the exact float value depending upon screen resolution.

In my app, I have used RelativeLayout and ImageViews within it, and set the margins of images using setMargins(), as this method uses pixels in int for its top, left, bottom and right values, how can I set these values using DPI factor I got? (which is a float). We have Math.floor() but I'm positioning images at very particular locations using pixels, and DPI factor returned by method has very specific value at decimal places which can't be ignored, so casting to int doesn't work for me.

Update

Also, I use lp.setMargins(100,200,0,0); to set the margins, what modification I'll be making in it to use DPI factor I recieved from device?

P.S. I know its more a mathematical issue rather than programming, but I'm poor with math, sorry.

回答1:

Looks like I was too early to ask the question instead of fiddling myself, but also noticed that I'm not AT ALL the first to face this issue.

So, here's solution I found.

I created a following method in my Activity class.

private int px(float dips)
{
    float DP = getResources().getDisplayMetrics().density;
    return Math.round(dips * DP);
}

This would convert given dp value into appropriate pixels. You can make the variable DP used in method to be global and initialize it in your onCreate() method rather than within px(), just to make method execute fast.

Usage:

lp.setMargins(px(100),px(200), 0, 0);

OR, if you don't create px() just for this and have DP as global.

lp.setMargins(100 * Math.round(DP), 200 * Math.round(DP), 0, 0);

However, using method makes it look much cleaner and readable. :-)