98

setWidth(int pixel) 是否使用与设备无关的像素或物理像素作为单位?例如,setWidth(100) 是否将视图的宽度设置为 100 dips 或 100 pxs?

谢谢。

4

7 回答 7

226

它使用像素,但我确定您想知道如何使用 dips 代替。答案在TypedValue.applyDimension(). 以下是如何在代码中将 dips 转换为 px 的示例:

// Converts 14 dip into its equivalent px
Resources r = getResources();
int px = Math.round(TypedValue.applyDimension(
    TypedValue.COMPLEX_UNIT_DIP, 14,r.getDisplayMetrics()));
于 2010-03-09T05:06:18.383 回答
27

在代码中获得恒定数量的 DIP 的正确方法是创建一个包含 dp 值的资源 XML 文件,有点像:

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

然后像这样引用代码中的资源:

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

您返回的浮点数将根据设备的像素密度进行相应缩放,因此您无需在整个应用程序中不断复制转换方法。

于 2013-02-17T14:15:27.477 回答
10

方法 setWidth(100),将 100 px 设置为宽度(不在 dp 中)。因此您可能会在不同的 android 手机上遇到宽度变化问题。因此使用 dp 中的测量而不是像素。使用下面的代码以 dp 获取样本宽度的测量= 300 像素,高度 = 400 像素。

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

int Height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 400, getResources().getDisplayMetrics());
于 2014-11-01T06:35:38.220 回答
4
float dps = 100;
float pxs = dps * getResources().getDisplayMetrics().density;

来源(@Romain Guy)

于 2015-02-14T16:13:43.360 回答
2

基于以上对我来说很好的答案,我生成了一些辅助方法,只需将它们添加到您的实用程序中即可在整个项目中使用它们。

   // value in DP
   public static int getValueInDP(Context context, int value){
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, context.getResources().getDisplayMetrics());
    }

    public static float getValueInDP(Context context, float value){
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, context.getResources().getDisplayMetrics());
    }

    // value in PX
    public static int getValueInPixel(Context context, int value){
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, value, context.getResources().getDisplayMetrics());
    }

    public static float getValueInPixel(Context context, float value){
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, value, context.getResources().getDisplayMetrics());
    }
于 2019-08-27T12:27:08.617 回答
0

像素当然,该方法要求像素作为参数。

于 2010-03-09T04:33:16.780 回答
0

Kotlin 扩展函数将像素转换为 dp

fun Context.pxToDp(value: Float):Int{
    val r: Resources = resources
    return TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_DIP, value, r.displayMetrics
    ).roundToInt()
}
于 2021-07-06T10:22:02.530 回答