Android: 'dp' To 'px' Conversion?
Solution 1:
It depends on the context.
If the dp value is used in a context that implies size, like the android:layout_width
attribute, the logic described for Resources.getDimensionPixelSize() will be used. That is, the px value will be rounded to the nearest integer value, with the special case that if px > 0, then the actual value will be at least 1.
If the dp value is used in a context that implies offset, like the android:insetLeft
attribute of the Inset Drawable, the logic described for Resources.getDimensionPixelOffset() will be used. That is, the px value will simply be truncated to an integer value.
Sometimes the unmodified floating point value is used, such as for the android:dashWidth
attribute of the <stroke/>
tag in a Shape Drawable, but this is pretty rare. Usually either the size or the offset logic is used, even if the floating point value could be used.
Solution 2:
If what I've read is correct, 1.5px means the single '1' pixel is a color specified, and the .5 of a pixel surrounding it will be a blend with the '1' pixel and a pixel next to it.
E.g.
| A | AB | B |
A is 1.5px and B is 1.5x, therefore the pixel in-between is a mixture of both.
So using that, two pixels next to each other will be blended together e.g with a 1px display
| X | Y |
Now with a 1.5px display:
| XY | YX | It becomes mix of both! but the pixel set as X will be more X than the pixel set as Y
Solution 3:
px is one pixel. scale-independent pixels ( sp ) and density-independent pixels ( dip ) you want to use sp for font sizes and dip for everything else.
dip==dp
from here http://developer.android.com/guide/topics/resources/more-resources.html#Dimension
px
Pixels - corresponds to actual pixels on the screen.
in
Inches - based on the physical size of the screen.
mm
Millimeters - based on the physical size of the screen.
pt
Points - 1/72of an inch based on the physical size of the screen.
dp
Density-independent Pixels - an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Note: The compiler accepts both "dip"and"dp", though "dp"is more consistent with"sp".
sp
Scale-independent Pixels - this islike the dp unit, but it is also scaled by the user's font size preference. It is recommend you use this unit when specifying font sizes, so they will be adjusted for both the screen density and user's preference.
Solution 4:
I think that would be the best solution 'cause it is standard method:
int valueInPx= (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_PX, valueInDp, getResources().getDisplayMetrics());
Post a Comment for "Android: 'dp' To 'px' Conversion?"