Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert dip to px in Android

Tags:

android

I had written method to get the pixels from dip but it is not working. It give me runtime error.

Actually I was running this method in separate class and initialized in my Activity class

Board board = new Board(this); board.execute(URL); 

This code runs asynchronously. Please help me.

public float getpixels(int dp){     //Resources r = boardContext.getResources();     //float px = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpis, r.getDisplayMetrics());              final float scale = this.boardContext.getResources().getDisplayMetrics().density;     int px = (int) (dp * scale + 0.5f);      return px; } 
like image 447
user961524 Avatar asked Dec 06 '11 11:12

user961524


People also ask

Is dp same as PX android?

Definitions. px or dot is a pixel on the physical screen. dpi are pixels per inch on the physical screen and represent the density of the display. dip or dp are density-indenpendant pixels, i.e. they correspond to more or less pixels depending on the physical density.

How many pixels is 1dp?

If device-independent pixel (dp) is used as the unit of length, then the operating system of the device maps the dp value to a corresponding number of pixels based on the resolution of the device screen. For this mapping, 1 dp is considered to be equal to 1 pixel on a 160 dpi resolution screen.

What is dp in Android?

One dp is a virtual pixel unit that's roughly equal to one pixel on a medium-density screen (160dpi; the "baseline" density). Android translates this value to the appropriate number of real pixels for each other density.

What is dp and SP in Android?

sp stands for scale-independent pixels. dp or dip (just use dp in your code if you're cool) stands for density-independent pixels.


2 Answers

Try this:

Java

public static float dipToPixels(Context context, float dipValue) {     DisplayMetrics metrics = context.getResources().getDisplayMetrics();     return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, metrics); } 

Kotlin

fun Context.dipToPixels(dipValue: Float) =     TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, resources.displayMetrics) 
like image 63
Dmytro Danylyk Avatar answered Oct 10 '22 10:10

Dmytro Danylyk


You can add the dp value in dimen.xml and use

int pixels = getResources().getDimensionPixelSize(R.dimen.idDimension); 

It's easier...

like image 32
juancazalla Avatar answered Oct 10 '22 12:10

juancazalla