我已经为分辨率为480x800的Pantech设备创建了以像素为单位的高度和宽度的应用程序。
我需要转换G1设备的高度和宽度。 我认为将其转换为dp将解决问题,并为两个设备提供相同的解决方案。
有没有什么简单的方法将像素转换为dp? 有什么建议吗?
我已经为分辨率为480x800的Pantech设备创建了以像素为单位的高度和宽度的应用程序。
我需要转换G1设备的高度和宽度。 我认为将其转换为dp将解决问题,并为两个设备提供相同的解决方案。
有没有什么简单的方法将像素转换为dp? 有什么建议吗?
当前回答
上面有很多很棒的解决方案。然而,我发现最好的解决方案是谷歌的设计:
https://design.google.com/devices/
其他回答
Xamarin的。安卓
float DpToPixel(float dp)
{
var resources = Context.Resources;
var metrics = resources.DisplayMetrics;
return dp * ((float)metrics.DensityDpi / (int)DisplayMetricsDensity.Default);
}
当你在制作一个自定义渲染器时,使它是非静态的是必要的
对我来说是这样的:
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int h = displaymetrics.heightPixels;
float d = displaymetrics.density;
int heightInPixels=(int) (h/d);
您可以对宽度执行相同的操作。
android SDK中有一个默认的util: http://developer.android.com/reference/android/util/TypedValue.html
float resultPix = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,1,getResources().getDisplayMetrics())
因此,您可以使用以下公式从dp中指定的维度计算正确的像素数量
public int convertToPx(int dp) {
// Get the screen's density scale
final float scale = getResources().getDisplayMetrics().density;
// Convert the dps to pixels, based on density scale
return (int) (dp * scale + 0.5f);
}
如果您可以使用XML维度,这是非常简单的!
在res/values/ dimensions .xml中:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="thumbnail_height">120dp</dimen>
...
...
</resources>
然后在Java中:
getResources().getDimensionPixelSize(R.dimen.thumbnail_height);