Pixels converteren naar dp

Ik heb mijn applicatie gemaakt met de hoogte en breedte in pixels voor een Pantech-apparaat met een resolutie van 480x800.

Ik moet hoogte en breedte converteren voor een G1-apparaat.
Ik dacht dat het omzetten naar dp het probleem zou oplossen en dezelfde oplossing zou bieden voor beide apparaten.

Is er een gemakkelijke manier om pixels naar dp te converteren?
Suggesties?


Antwoord 1, autoriteit 100%

Java-code:

// Converts 14 dip into its equivalent px
float dip = 14f;
Resources r = getResources();
float px = TypedValue.applyDimension(
    TypedValue.COMPLEX_UNIT_DIP,
    dip,
    r.getDisplayMetrics()
);

Kotlin-code:

val dip = 14f
 val r: Resources = resources
 val px = TypedValue.applyDimension(
     TypedValue.COMPLEX_UNIT_DIP,
     dip,
     r.displayMetrics
 )

Kotlin-extensie:

val Number.toPx get() = TypedValue.applyDimension(
  TypedValue.COMPLEX_UNIT_DIP,
  this.toFloat(),
  Resources.getSystem().displayMetrics)

Antwoord 2, autoriteit 82%

/**
 * This method converts dp unit to equivalent pixels, depending on device density. 
 * 
 * @param dp A value in dp (density independent pixels) unit. Which we need to convert into pixels
 * @param context Context to get resources and device specific display metrics
 * @return A float value to represent px equivalent to dp depending on device density
 */
public static float convertDpToPixel(float dp, Context context){
    return dp * ((float) context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);
}
/**
 * This method converts device specific pixels to density independent pixels.
 * 
 * @param px A value in px (pixels) unit. Which we need to convert into db
 * @param context Context to get resources and device specific display metrics
 * @return A float value to represent dp equivalent to px value
 */
public static float convertPixelsToDp(float px, Context context){
    return px / ((float) context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);
}

Antwoord 3, autoriteit 27%

Bij voorkeur in een Util.java-klasse plaatsen

public static float dpFromPx(final Context context, final float px) {
    return px / context.getResources().getDisplayMetrics().density;
}
public static float pxFromDp(final Context context, final float dp) {
    return dp * context.getResources().getDisplayMetrics().density;
}

Antwoord 4, autoriteit 19%

float density = context.getResources().getDisplayMetrics().density;
float px = someDpValue * density;
float dp = somePxValue / density;

densityis gelijk aan

  • .75op ldpi(120dpi)
  • 1.0op mdpi(160dpi; baseline)
  • 1.5op hdpi(240dpi)
  • 2.0op xhdpi(320dpi)
  • 3.0op xxhdpi(480dpi)
  • 4.0op xxxhdpi(640dpi)

Gebruik deze online converterom met dpi-waarden te spelen.

BEWERKEN:
Het lijkt erop dat er geen 1:1 relatie is tussen dpi-bucket en density. Het lijkt erop dat de Nexus 5Xdie xxhdpiis, een densitywaarde heeft van 2.625(in plaats van 3). Bekijk het zelf in de Apparaatstatistieken.


Antwoord 5, autoriteit 12%

Je kunt deze .. gebruiken zonder context

public static int pxToDp(int px) {
    return (int) (px / Resources.getSystem().getDisplayMetrics().density);
}
public static int dpToPx(int dp) {
    return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
}

Zoals @Stan al zei .. het gebruik van deze aanpak kan problemen veroorzaken als het systeem de dichtheid verandert. Houd daar dus rekening mee!

Persoonlijk gebruik ik Context om dat te doen. Het is gewoon een andere benadering waarmee ik je wilde delen


Antwoord 6, autoriteit 9%

Als u de dimensie-XML kunt gebruiken, is dat heel eenvoudig!

In uw res/values/dimens.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="thumbnail_height">120dp</dimen>
    ...
    ...
</resources>

Vervolgens in uw Java:

getResources().getDimensionPixelSize(R.dimen.thumbnail_height);

Antwoord 7, autoriteit 7%

Volgens de Android Development Guide:

px = dp * (dpi / 160)

Maar vaak wil je dit anders uitvoeren wanneer je een ontwerp ontvangt dat in pixels wordt vermeld. Dus:

dp = px / (dpi / 160)

Als u op een 240DPI-apparaat staat, is deze verhouding 1,5 (zoals eerder vermeld), dus dit betekent dat een pictogram van 60 PX gelijk is aan 40 dopp in de toepassing.


Antwoord 8, Autoriteit 6%

zonder Context, elegante statische methoden:

public static int dpToPx(int dp)
{
    return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
}
public static int pxToDp(int px)
{
    return (int) (px / Resources.getSystem().getDisplayMetrics().density);
}

Antwoord 9, Autoriteit 4%

voor DP to Pixel

Maak een waarde in dimens.xml

<dimen name="textSize">20dp</dimen>

Krijg die waarde in pixelals:

int sizeInPixel = context.getResources().getDimensionPixelSize(R.dimen.textSize);

Antwoord 10, Autoriteit 4%

Voor iedereen die KOTLIN gebruikt:

val Int.toPx: Int
    get() = (this * Resources.getSystem().displayMetrics.density).toInt()
val Int.toDp: Int
    get() = (this / Resources.getSystem().displayMetrics.density).toInt()

Gebruik:

64.toPx
32.toDp

Antwoord 11, Autoriteit 4%

U kunt daarom de volgende formulator gebruiken om de juiste hoeveelheid pixels te berekenen vanuit een dimensie die is opgegeven in DP

public int convertToPx(int dp) {
    // Get the screen's density scale
    final float scale = getResources().getDisplayMetrics().density;
    // Convert the dps to pixels, based on density scale
    return (int) (dp * scale + 0.5f);
}

Antwoord 12, Autoriteit 4%

Het gebruik van KOTLIN-extensie maakt het beter

fun Int.toPx(context: Context): Int = (this * context.resources.displayMetrics.density).toInt()
fun Int.toDp(context: Context): Int = (this / context.resources.displayMetrics.density).toInt()

UPDATE:

Vanwege displayMetricsmaakt deel uit van Globale gedeelde bronnen , we kunnen Resources.getSystem()

gebruiken

val Float.toPx get() = this * Resources.getSystem().displayMetrics.density
val Float.toDp get() = this / Resources.getSystem().displayMetrics.density
val Int.toPx get() = (this * Resources.getSystem().displayMetrics.density).toInt()
val Int.toDp get() = (this / Resources.getSystem().displayMetrics.density).toInt()

Antwoord 13, Autoriteit 3%

Er is een standaard util in Android SDK:
http://developer.android.com/reference/android/util/typpedvalue.html

float resultPix = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,1,getResources().getDisplayMetrics())

Antwoord 14, Autoriteit 2%

KOTLIN

fun convertDpToPixel(dp: Float, context: Context): Float {
    return dp * (context.resources.displayMetrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
}
fun convertPixelsToDp(px: Float, context: Context): Float {
    return px / (context.resources.displayMetrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
}

Java

public static float convertDpToPixel(float dp, Context context) {
    return dp * ((float) context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);
}
public static float convertPixelsToDp(float px, Context context) {
    return px / ((float) context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);
}

Antwoord 15, autoriteit 2%

Dit zou u de conversie dp naar pixels moeten geven:

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

Dit zou u de conversiepixels naar dp moeten geven:

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

Antwoord 16

Waarschijnlijk de beste manier als u de dimensie binnen waarden/dimen heeft, is om de dimensie rechtstreeks uit de getDimension()-methode te halen, u krijgt de dimensie terug die al is omgezet in pixelwaarde.

context.getResources().getDimension(R.dimen.my_dimension)

Om dit beter uit te leggen,

getDimension(int resourceId) 

retourneert de dimensie die al is geconverteerd naar pixel AS A FLOAT.

getDimensionPixelSize(int resourceId)

zal hetzelfde teruggeven, maar afgekapt tot int, dus AS AN
INTEGER.

Zie Android-referentie


Antwoord 17

zoals dit:

public class ScreenUtils {
    public static float dpToPx(Context context, float dp) {
        if (context == null) {
            return -1;
        }
        return dp * context.getResources().getDisplayMetrics().density;
    }
    public static float pxToDp(Context context, float px) {
        if (context == null) {
            return -1;
        }
        return px / context.getResources().getDisplayMetrics().density;
    }
}

afhankelijk van Context, return float-waarde, statische methode

van: https://github.com/Trinea/android-common/blob/master/src/cn/trinea/android/common/util/ScreenUtils.java#L15


Antwoord 18

Elegantere benadering met behulp van de extensiefunctie van kotlin

/**
 * Converts dp to pixel
 */
val Int.dpToPx: Int get() = (this * Resources.getSystem().displayMetrics.density).toInt()
/**
 * Converts pixel to dp
 */
val Int.pxToDp: Int get() = (this / Resources.getSystem().displayMetrics.density).toInt()

Gebruik:

println("16 dp in pixel: ${16.dpToPx}")
println("16 px in dp: ${16.pxToDp}")

Antwoord 19

gebruik de TypedValueom Pixels naar dp te converteren.

Zoals de documentatie vermeldde: container voor een dynamisch getypte gegevenswaarde.

en gebruik de applyDimensionmethode:

public static float applyDimension (int unit, float value, DisplayMetrics metrics) 

die een uitgepakte complexe gegevenswaarde met een dimensie converteert naar de uiteindelijke drijvende-kommawaarde zoals de volgende:

Resources resource = getResources();
float dp = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 69, resource.getDisplayMetrics());

Hoop dat dat helpt .


Antwoord 20

float scaleValue = getContext().getResources().getDisplayMetrics().density;
int pixels = (int) (dps * scaleValue + 0.5f);

Antwoord 21

Als u een prestatiekritische toepassing ontwikkelt, overweeg dan de volgende geoptimaliseerde klasse:

public final class DimensionUtils {
    private static boolean isInitialised = false;
    private static float pixelsPerOneDp;
    // Suppress default constructor for noninstantiability.
    private DimensionUtils() {
        throw new AssertionError();
    }
    private static void initialise(View view) {
        pixelsPerOneDp = view.getResources().getDisplayMetrics().densityDpi / 160f;
        isInitialised = true;
    }
    public static float pxToDp(View view, float px) {
        if (!isInitialised) {
            initialise(view);
        }
        return px / pixelsPerOneDp;
    }
    public static float dpToPx(View view, float dp) {
        if (!isInitialised) {
            initialise(view);
        }
        return dp * pixelsPerOneDp;
    }
}

Antwoord 22

Zo werkt het voor mij:

DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int  h = displaymetrics.heightPixels;
float  d = displaymetrics.density;
int heightInPixels=(int) (h/d);

Je kunt hetzelfde doen voor de breedte.


Antwoord 23

Veel geweldige oplossingen hierboven. De beste oplossing die ik heb gevonden, is echter het ontwerp van Google:

https://design.google.com/devices/


Antwoord 24

Dp converteren naar pixel

public static int dp2px(Resources resource, int dp) {
    return (int) TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_DIP,
        dp,resource.getDisplayMetrics()
    );
}

Om pixel naar dp te converteren.

public static float px2dp(Resources resource, float px)  {
    return (float)TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_PX,
        px,
        resource.getDisplayMetrics()
    );
}

waar bron context.getResources() is.


Antwoord 25

Je moet dp net zo gebruiken als pixels. Dat is alles wat ze zijn; onafhankelijke pixels weergeven. Gebruik dezelfde cijfers als op een scherm met gemiddelde dichtheid en de grootte zal op magische wijze correct zijn op een scherm met hoge dichtheid.

Het klinkt echter alsof u de optie fill_parent in uw lay-outontwerp nodig hebt. Gebruik fill_parent wanneer u wilt dat uw weergave of besturingselement wordt uitgebreid tot alle resterende grootte in de bovenliggende container.


Antwoord 26

PXen DPzijn verschillend, maar vergelijkbaar.

DPis de resolutie als je alleen rekening houdt met de fysieke grootte van het scherm. Wanneer u DPgebruikt, wordt uw lay-out geschaald naar andere schermen van vergelijkbare grootte met verschillende pixel-dichtheden.

Af en toe wil je echter pixels, en als je met afmetingen in code omgaat, heb je altijd te maken met echte pixels, tenzij je ze converteert.

Dus op een Android-apparaat, een hdpi-scherm van normale grootte, is 800x480 is 533x320in DP(denk ik). Om DPom te zetten in pixels /1.5, om *1.5terug te converteren. Dit is alleen voor de ene schermgrootte en dpi, het zou veranderen afhankelijk van het ontwerp. Onze artiesten geven me echter pixelsen ik converteer naar DPmet de bovenstaande 1.5vergelijking.


Antwoord 27

private fun toDP(context: Context,value: Int): Int {
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
        value.toFloat(),context.resources.displayMetrics).toInt()
}

Antwoord 28

Als u Integerwaarden wilt, dan zal het gebruik van Math.round() de float afronden op het dichtstbijzijnde gehele getal.

public static int pxFromDp(final float dp) {
        return Math.round(dp * Resources.getSystem().getDisplayMetrics().density);
    }

Antwoord 29

Het beste antwoord komt van het Android-framework zelf: gebruik gewoon deze gelijkheid…

public static int dpToPixels(final DisplayMetrics display_metrics, final float dps) {
    final float scale = display_metrics.density;
    return (int) (dps * scale + 0.5f);
}

(converteert dp naar px)


Antwoord 30

Dit werkt voor mij (C#):

int pixels = (int)((dp) * Resources.System.DisplayMetrics.Density + 0.5f);

Other episodes