如何将dp转换为像素,并在android中使用它绘制画布

如何将dp转换为像素,并在android中使用它绘制画布,android,canvas,Android,Canvas,我正在尝试将dp转换为像素。我正在使用这种方法: //Converts device pixels to regular pixels to draw private float dpToPixel(float dp) { DisplayMetrics metrics = this.getResources().getDisplayMetrics(); float px = dp * (metrics.densityDpi/160f); return px; } 然后我

我正在尝试将dp转换为像素。我正在使用这种方法:

//Converts device pixels to regular pixels to draw
private float dpToPixel(float dp) {
    DisplayMetrics metrics = this.getResources().getDisplayMetrics();
    float px = dp * (metrics.densityDpi/160f);
    return px;
}
然后我尝试从dimen.xml文件中的变量获取dp,如下所示:

int buttonWidth = (int) dpToPixel(R.dimen.buttonHeight);
然后,我创建了一个缩放位图,宽度为
buttonWidth
变量。
最后我把它画到画布上。但当我尝试运行它时,什么也不显示。有人能帮忙吗?

我认为您的问题中可能有输入错误,或者您确实没有加载高度值-您实际上加载了一个表示资源id的数字。应该是:

int buttonWidth = (int) dpToPixel(getResorces().getDimension(R.dimen.buttonHeight));
但是……您不需要自己进行转换:

getResources().getDimensionPixelSize(R.dimen.buttonHeight);
将dp转换为像素

private int dpToPx(int dp) {
    Resources r = getResources();
    return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}
private int dpToPx(int dp) {
    Resources r = getResources();
    return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}