Morcl174
Morcl174

Reputation: 93

how-to get dimens (px format not dp) in px in java code?

how can I read a dimen in java.

<dimen name="something">10px</dimen>

if I try

getResources().getDimensionPixelOffset(R.dimen.something)

it returns 18 instead of 10. the result is bigger than expected, but if R.dimen.something is 540 px the result is 180. i don't understand this conversion. is there a way to get original value from dimen.

i need the values in px for drawing (non visible, inflated) views to canvas and saving the result as jpg. the result should always look the same and not depend on dpi.

<integer name="something">10</integer>

is not an option, because it cannot be used in xml.

EDIT1:

i don't know why, but an other device returns the expected values. maybe it's a bug in the cyanogenmod version i'm using on my main device

EDIT2:

it was a bug, after updating my cyanogenmod version it work

Upvotes: 1

Views: 3082

Answers (2)

Sakchham
Sakchham

Reputation: 1739

If you have a look at the documentation of Resources#getDimensions(int) it reads as follows

float getDimension (int id)
Retrieve a dimensional for a particular resource ID. Unit conversions are based on the current DisplayMetrics associated with the resources.

which means if your dimension definition looks like this
<dimen name="dimen_pix">10px</dimen>

getResources().getDimensions(R.dimen.dimen_pix) would return 10.0

and if the dimension is specified as a dip
<dimen name="dimen_dip">10dp</dimen>

getResources().getDimensions(R.dimen.dimen_dip)
would return 10.0 x density density here is your screen's relative pixel density with respect to a mdpi screen (160ppi)

If you are looking to get the exact defined value of a dip dimension you can use the following code snippet

float screenDensity = getResources().getDisplayMetrics().density;
float dipDimension = getResources().getDimension(R.dimen.test_dimen);
float actualDimension = dipDimension/screenDensity; //required value

Upvotes: 2

emrah
emrah

Reputation: 140

try one of these

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

or

getResources().getDimension(R.dimen.something);

Upvotes: 2

Related Questions