How to define a pixel independent height in an onDraw() method

二次信任 提交于 2019-12-04 06:16:02

multiply your pixel values by getResources().getDisplayMetrics().density to make pixels density-independent. If you draw text, you might want to use scaledDensity instead.

density = 1 on mdpi, 1.5 on hdpi, and 0.75 on ldpi i believe.

To complete the answer, some source code:

Either use the following when dealing with views or images

int px = getResources().getDisplayMetrics().density * dp;  

Or, when dealing with text:

int px = getResources().getDisplayMetrics().scaledDensity * sp;

To get px values from dp values, calculate

int px = getResources().getDisplayMetrics().density * dp;

I recommend to place a static method somewhere which takes the dp value as parameter in order to do this with less code. E.g. I created a class "ResolutionHelper" which is initialized with the correct density value on app start and which has a static method "dipToPx(int dip) that can then used from anywhere.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!