Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting dip to pixels yielding the same value

I need to convert density independent pixels to pixels in my activity. I tried using this method in my onCreate

float pix = dipValue * getResources().getDisplayMetrics().density;
pixel = Math.round(pix);

I tried another method

Resources r = getResources();
float pix = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 35,r.getDisplayMetrics());
value = Math.round(pix);

both are yielding the same value. I think the problem is not with the method but with the resources. Should I make any changes in the Manifest file like

<supports-screens android:resizeable=["true"| "false"]
              android:smallScreens=["true" | "false"]
              android:normalScreens=["true" | "false"]
              android:largeScreens=["true" | "false"]
              android:xlargeScreens=["true" | "false"]
              android:anyDensity=["true" | "false"]
              android:requiresSmallestWidthDp="integer"
              android:compatibleWidthLimitDp="integer"
              android:largestWidthLimitDp="integer"/>

There is a similar question to mine. But it is not solving my problem. Help me out.

like image 203
darsh Avatar asked Jan 17 '23 17:01

darsh


1 Answers

Have you tried

px = dp * (dpi / 160)

The density-independent pixel is equivalent to one physical pixel on a 160 dpi screen, which is the baseline density assumed by the system for a "medium" density screen. At runtime, the system transparently handles any scaling of the dp units, as necessary, based on the actual density of the screen in use. The conversion of dp units to screen pixels is simple: px = dp * (dpi / 160). For example, on a 240 dpi screen, 1 dp equals 1.5 physical pixels. You should always use dp units when defining your application's UI, to ensure proper display of your UI on screens with different densities.

Please check this link for more details.

like image 173
silwar Avatar answered Jan 20 '23 02:01

silwar