Reputation: 707
Suppose I have a value say :- 360dp for a device that is: Resolution: 1280x800 sw800dp mdpi
Now I know this dp value works well for the device. How do I calculate the dp value for a device that is: 1024x600 sw600dp
Edit 1: Maybe I didn't make myself clear. I know what the width must be in dp for a give device typeA with certain resolution R1. How do I calculate the dp value should be for another device typeB with resolution R2? mdpi
and similarly for a device that is: 2560x1600 sw800dp xhdpi
I guess what I want to know is how does the math work. What would be the way to calculate the dp value to put in different values files.
Upvotes: 2
Views: 352
Reputation: 5644
A set of six generalized densities: ldpi (low) -120dpi, mdpi (medium) -160dpi, hdpi (high) -240dpi, xhdpi (extra-high) -320dpi, xxhdpi (extra-extra-high) -480dpi, xxxhdpi (extra-extra-extra-high) -640dpi.
If running on mdpi device, 150x150 px image will take up 150*150 dp of screen space.
If running on hdpi device, 150x150 px image will take up 100*100 dp of screen space.
If running on xhdpi device, 150x150 px image will take up 75*75 dp of screen space.
Upvotes: 1
Reputation: 1223
i think below class is complete solution for your present as well as futer problems ,
public class DisplayUtil
{
private static int DisplayWidthPixels = 0;
private static int DisplayheightPixels = 0;
private static void getDisplayMetrics(Context context)
{
DisplayMetrics dm = new DisplayMetrics();
((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);
DisplayWidthPixels = dm.widthPixels;
DisplayheightPixels = dm.heightPixels;
}
public static int getDisplayWidthPixels(Context context)
{
if (context == null)
{
return -1;
}
if (DisplayWidthPixels == 0)
{
getDisplayMetrics(context);
}
return DisplayWidthPixels;
}
public static int getDisplayheightPixels(Context context)
{
if (context == null)
{
return -1;
}
if (DisplayheightPixels == 0)
{
getDisplayMetrics(context);
}
return DisplayheightPixels;
}
public static int px2dip(Context context, float pxValue)
{
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
public static int dip2px(Context context, float dipValue)
{
if (context == null)
{
return 0;
}
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
public static int px2sp(Context context, float pxValue)
{
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (pxValue / fontScale + 0.5f);
}
public static int sp2px(Context context, float spValue)
{
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}
}
ex. just you have to call DisplayUtil.Method-Name !
Upvotes: 1
Reputation: 1086
And here we go... We have a online calculator...
https://pixplicity.com/dp-px-converter/
I had a similar problem, so tried this and it worked.
Upvotes: 0