getDimension()/getDimensionPixelSize() - mutliplier issue

后端 未结 5 1075
悲哀的现实
悲哀的现实 2021-02-07 06:07

So I have android 2.3.5 device which is NORMAL/HDPI. I have a dimens.xml in my project:

...
    20sp         


        
5条回答
  •  隐瞒了意图╮
    2021-02-07 06:45

    Method getDimension() converts dp or sp values into pixels based on current screen density. This is very useful as you don't have to do it on your own, when you want to set in Java width or text size (they accepts only pixels).

    But if you need original sp or dp you could do "reverse engineering".

    Step 1. Check current scale ratio (based on screen density):

    float scaleRatio = getResources().getDisplayMetrics().density;
    

    Step 2. Get dimension from dimens.xml

    float dimenPix = getResources().getDimension(R.dimen.your_dimen_name);
    

    Step 3. Do some math

    float dimenOrginal = dimenPix/scaleRatio;
    

    Remarks:

    • usually you need int for dimension methods (like setWidth()), so you have to convert float result to int for instance using Math.round()
    • more accurate result when rounding to int you could get using such formula (dimenPix-0.5f)/scaleRatio
    • in case of sp you could take also into account user preferences about text scale

    Read more about dimensions in Android: http://android4beginners.com/2013/07/appendix-c-everything-about-sizes-and-dimensions-in-android/

提交回复
热议问题