Programing

공식 px에서 dp로, dp에서 px로 안드로이드

lottogame 2020. 6. 15. 08:21
반응형

공식 px에서 dp로, dp에서 px로 안드로이드


밀도 독립 픽셀과 그 반대로 가변 량의 픽셀을 계산하려고합니다.

이 공식 (px to dp): dp = (int)(px / (displayMetrics.densityDpi / 160));은 0으로 나눠지기 때문에 작은 장치에서는 작동하지 않습니다.

이것은 내 dp to px 공식입니다.

px = (int)(dp * (displayMetrics.densityDpi / 160));

누군가 나에게 포인터를 줄 수 있습니까?


참고 : 위의 널리 사용되는 솔루션은을 기반으로 displayMetrics.density합니다. 그러나 문서에서는이 값이 반올림 값이며 화면 '버킷'과 함께 사용된다고 설명합니다. 예 : 내 Nexus 10에서는 2를 반환하며 실제 값은 298dpi (실제) / 160dpi (기본값) = 1.8625입니다.

요구 사항에 따라 다음과 같이 달성 할 수있는 정확한 변환이 필요할 수 있습니다.

[편집] 이것은 여전히 ​​화면 버킷을 기반으로하기 때문에 안드로이드의 내부 dp 장치와 혼합되어서는 안됩니다. 다른 장치에서 동일한 실제 크기를 렌더링해야하는 장치를 원하는 경우이 옵션을 사용하십시오.

dp를 픽셀로 변환 :

public int dpToPx(int dp) {
    DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
    return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));     
}

픽셀을 dp로 변환 :

public int pxToDp(int px) {
    DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
    return Math.round(px / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
}

xdpi 및 ydpi 속성이 있지만 구별하고 싶을 수도 있지만 이러한 값이 크게 다른 화면은 상상할 수 없습니다.


다음 공식을 사용하여 문제를 해결했습니다. 다른 사람들이 혜택을 누리 길 바랍니다.

dp에서 px로 :

displayMetrics = context.getResources().getDisplayMetrics();
return (int)((dp * displayMetrics.density) + 0.5);

px에서 dp로 :

displayMetrics = context.getResources().getDisplayMetrics();
return (int) ((px/displayMetrics.density)+0.5);

px에서 dp로 :

int valueInpx = ...;
int valueInDp= (int) TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP, valueInpx , getResources()
                .getDisplayMetrics());

단위에서 픽셀 getResources().getDimensionPixelSize(R.dimen.your_dimension)로 변환하기 위해 전화하십시오.dp


효율적인 방법

DP에서 픽셀로 :

private int dpToPx(int dp)
{
    return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
}

픽셀에서 DP로 :

private int pxToDp(int px)
{
    return (int) (px / Resources.getSystem().getDisplayMetrics().density);
}

이것이 도움이되기를 바랍니다.


이 기능 사용

private int dp2px(int dp) {
    return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
}

px = dp * (dpi / 160)

dp = px * (160 / dpi)

대부분의 경우 변환 함수가 자주 호출됩니다. 메모를 추가하여 최적화 할 수 있습니다. 따라서 함수가 호출 될 때마다 계산하지 않습니다.

계산 된 값을 저장할 HashMap을 선언 해 봅시다.

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

픽셀 값을 계산하는 함수 :

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

        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        float px = dp * (metrics.densityDpi / 160f);
        return px;

    }

HashMap에서 값을 반환하고 이전 값의 레코드를 유지하는 메모 함수입니다.

Java에서 메모를 다른 방식으로 구현할 수 있습니다. 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은 Lambda 기능을 지원합니다 .

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

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

감사.


이것을 시도하십시오 http://labs.skinkers.com/content/android_dp_px_calculator/


아래 funtions는 여러 기기에서 잘 작동했습니다.

https://gist.github.com/laaptu/7867851 에서 가져옵니다.

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);
}

[DisplayMatrics][1]화면 밀도를 사용 하고 결정할 수 있습니다 . 이 같은:

int pixelsValue = 5; // margin in pixels
float d = context.getResources().getDisplayMetrics().density;
int margin = (int)(pixelsValue * d);

기억 하듯이 오프셋에는 바닥을 사용하고 너비에는 반올림을 사용하는 것이 좋습니다.


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);

    }

variation on ct_robs answer above, if you are using integers, that not only avoids divide by 0 it also produces a usable result on small devices:

in integer calculations involving division for greatest precision multiply first before dividing to reduce truncation effects.

px = dp * dpi / 160 dp = px * 160 / dpi

5 * 120 = 600 / 160 = 3

instead of

5 * (120 / 160 = 0) = 0

if you want rounded result do this

px = (10 * dp * dpi / 160 + 5) / 10 dp = (10 * px * 160 / dpi + 5) / 10

10 * 5 * 120 = 6000 / 160 = 37 + 5 = 42 / 10 = 4


with help of other answers I wrote this function.

public static int convertToPixels(Context context, int nDP)
{
        final float conversionScale = context.getResources().getDisplayMetrics().density; 
        return (int) ((nDP * conversionScale) + 0.5f) ;
}

Here's a other way to do it using kotlin extensions:

val Int.dpToPx: Int
    get() = Math.round(this * Resources.getSystem().displayMetrics.density)

val Int.pxToDp: Int
    get() = Math.round(this / Resources.getSystem().displayMetrics.density)

and then it can be used like this from anywhere

12.dpToPx

244.pxToDp

참고URL : https://stackoverflow.com/questions/8309354/formula-px-to-dp-dp-to-px-android

반응형