px android,公式px到dp,dp到px android

Note: The widely used solution above is based on displayMetrics.density. However, the docs explain that this value is a rounded value, used with the screen 'buckets'. Eg. on my Nexus 10 it returns 2, where the real value would be 298dpi (real) / 160dpi (default) = 1.8625.

Depending on your requirements, you might need the exact transformation, which can be achieved like this:

[Edit] This is not meant to be mixed with Android's internal dp unit, as this is of course still based on the screen buckets. Use this where you want a unit that should render the same real size on different devices.

Convert dp to pixel:

public int dpToPx(int dp) {

DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();

return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));

}

Convert pixel to dp:

public int pxToDp(int px) {

DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();

return Math.round(px / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));

}

Note that there are xdpi and ydpi properties, you might want to distinguish, but I can't imagine a sane display where these values differ greatly.

I solved my problem by using the following formulas. May other people benefit from it.

dp to px:

displayMetrics = context.getResources().getDisplayMetrics();

return (int)((dp * displayMetrics.density) + 0.5);

px to dp:

displayMetrics = context.getResources().getDisplayMetrics();

return (int) ((px/displayMetrics.density)+0.5);

px to dp:

int valueInpx = ...;

int valueInDp= (int) TypedValue.applyDimension(

TypedValue.COMPLEX_UNIT_DIP, valueInpx , getResources()

.getDisplayMetrics());

Just call getResources().getDimensionPixelSize(R.dimen.your_dimension) to convert from dp units to pixels

Efficient way ever

DP to Pixel:

private int dpToPx(int dp)

{

return (int) (dp * Resources.getSystem().getDisplayMetrics().density);

}

Pixel to DP:

private int pxToDp(int px)

{

return (int) (px / Resources.getSystem().getDisplayMetrics().density);

}

Hope this will help you.

Use This function

private int dp2px(int dp) {

return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());

}

px = dp * (dpi / 160)

dp = px * (160 / dpi)

In most of the cases, conversion functions are called frequently. We can optimize it by adding memoization. So,it does not calculate every-time the function is called.

Let's declare a HashMap which will store the calculated values.

private static Map pxCache = new HashMap<>();

A function which calculates pixel values :

public static float calculateDpToPixel(float dp, Context context) {

Resources resources = context.getResources();

DisplayMetrics metrics = resources.getDisplayMetrics();

float px = dp * (metrics.densityDpi / 160f);

return px;

}

A memoization function which returns the value from HashMap and maintains the record of previous values.

Memoization can be implemented in different ways in Java. For Java 7 :

public static float convertDpToPixel(float dp, final Context context) {

Float f = pxCache.get(dp);

if (f == null) {

synchronized (pxCache) {

f = calculateDpToPixel(dp, context);

pxCache.put(dp, f);

}

}

return f;

}

Java 8 supports Lambda function :

public static float convertDpToPixel(float dp, final Context context) {

pxCache.computeIfAbsent(dp, y ->calculateDpToPixel(dp,context));

}

Thanks.

Below funtions worked well for me across devices.

public static float convertPixelsToDp(float px){

DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();

float dp = px / (metrics.densityDpi / 160f);

return Math.round(dp);

}

public static float convertDpToPixel(float dp){

DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();

float px = dp * (metrics.densityDpi / 160f);

return Math.round(px);

}

You can use [DisplayMatrics][1] and determine the screen density. Something like this:

int pixelsValue = 5; // margin in pixels

float d = context.getResources().getDisplayMetrics().density;

int margin = (int)(pixelsValue * d);

As I remember it's better to use flooring for offsets and rounding for widths.

If you're looking for an online calculator for converting DP, SP, inches, millimeters, points or pixels to and from one another at different screen densities, this is the most complete tool I know of.

// for getting in terms of Decimal/Float

public static float convertPixelsToDp(float px, Context context) {

Resources resources = context.getResources();

DisplayMetrics metrics = resources.getDisplayMetrics();

float dp = px / (metrics.densityDpi / 160f);

return Math.round(dp);

}

public static float convertDpToPixel(float dp, Context context) {

DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();

float px = dp * (metrics.densityDpi / 160f);

return Math.round(px);

}

// for getting in terms of Integer

private int convertPxToDp(int px, Context context) {

Resources resources = context.getResources();

return Math.round(px / (resources.getDisplayMetrics().xdpi / DisplayMetrics.DENSITY_DEFAULT));

}

private int convertDpToPx(int dp, Context context) {

Resources resources = context.getResources();

return Math.round(dp * (resources.getDisplayMetrics().xdpi / DisplayMetrics.DENSITY_DEFAULT));

}

________________________________________________________________________________

public static float convertPixelsToDp(float px){

DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();

float dp = px / (metrics.densityDpi / 160f);

return Math.round(dp);

}

public static float convertDpToPixel(float dp){

DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();

float px = dp * (metrics.densityDpi / 160f);

return Math.round(px);

}

private int convertDpToPx(int dp){

return Math.round(dp*(getResources().getDisplayMetrics().xdpi/DisplayMetrics.DENSITY_DEFAULT));

}

private int convertPxToDp(int px){

return Math.round(px/(Resources.getSystem().getDisplayMetrics().xdpi/DisplayMetrics.DENSITY_DEFAULT));

}

Feel free to use this method I wrote:

int dpToPx(int dp)

{

return (int) (dp * getResources().getDisplayMetrics().density + 0.5f);

}

The answer accepted above is not fully accurate. According to information obtained by inspecting Android source code:

Resources.getDimension() and getDimensionPixelOffset()/getDimensionPixelSize() differ only in that the former returns float while the latter two return the same value rounded to int appropriatelly. For all of them, the return value is in raw pixels.

All three functions are implementedy by calling Resources.getValue() and converting thus obtained TypedValue by calling TypedValue.complexToDimension(), TypedValue.complexToDimensionPixelOffset() and TypedValue.complexToDimensionPixelSize(), respectively.

Therefore, if you want to obtain "raw" value together with the unit specified in XML source, call Resources.getValue() and use methods of the TypedValue class.

DisplayMetrics displayMetrics = contaxt.getResources()

.getDisplayMetrics();

int densityDpi = (int) (displayMetrics.density * 160f);

int ratio = (densityDpi / DisplayMetrics.DENSITY_DEFAULT);

int px;

if (ratio == 0) {

px = dp;

} else {

px = Math.round(dp * ratio);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值