Does setWidth(int pixels) use dip or px?

别等时光非礼了梦想. 提交于 2019-11-26 23:21:00
Daniel Lew

It uses pixels, but I'm sure you're wondering how to use dips instead. The answer is in TypedValue.applyDimension(). Here's an example of how to convert dips to px in code:

// Converts 14 dip into its equivalent px
Resources r = getResources();
int px = Math.round(TypedValue.applyDimension(
    TypedValue.COMPLEX_UNIT_DIP, 14,r.getDisplayMetrics()));

The correct way to obtain a constant number of DIPs in code is to create a resources XML file containing dp values a bit like:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="image_width">100dp</dimen>
    <dimen name="image_height">75dp</dimen>
</resources>

Then refer to the resource in your code like so:

float width = getResources().getDimension(R.dimen.image_width));
float height = getResources().getDimension(R.dimen.image_height));

The float you have returned will be scaled accordingly for the pixel density of the device and so you don't need to keep replicating a conversion method throughout your application.

Method setWidth(100), set 100 px as width(not in dp).So you may face width varying problems on different android phones.So use measurement in dp instead of pixels.Use the below code to get measurement in dp of sample width=300px and height=400px.

int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300, getResources().getDisplayMetrics());

int Height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 400, getResources().getDisplayMetrics());
pomber
float dps = 100;
float pxs = dps * getResources().getDisplayMetrics().density;

Source (@Romain Guy)

Josnidhin

Pixels of course, the method is asking for pixels as parameter.

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