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; }
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.
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.
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.
sp stands for scale-independent pixels. dp or dip (just use dp in your code if you're cool) stands for density-independent pixels.
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)
You can add the dp value in dimen.xml and use
int pixels = getResources().getDimensionPixelSize(R.dimen.idDimension);
It's easier...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With