我有一个 SurfaceView 和 TextView,我在上面绘制文本
Paint p = new Paint();
p.p.setTextSize(14);
canvas.drawText(....
TextView text =...
text.setTextSize(14);
在某些设备上,两个文本看起来完全一样。但在模拟器和 Samsung Galaxy III 上, Canvas 上的文字要小两倍。为什么?如何在所有设备上获得相同的尺寸?
SurfaceView 和TextView 同时出现在屏幕上。 TextView 位于多个图层上并覆盖在 SurcafeView 的 Canvas 上。
最好的问候
最佳答案
您必须在 android 中使用设备独立像素 (dp/dip) 才能在所有设备上获得相同的尺寸。在文本的情况下,存在与比例无关的像素 (sp)。查看更多关于这些的信息以便更好地理解。
To convert Pixel value into dp use the following code:
public static float convertPixelsToDp(float px,Context context){
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
float dp = px / (metrics.densityDpi / 160f);
return dp;
}
To convert dp value into pixel use the following code:
public static float convertDpToPixel(float dp,Context context){
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
float px = dp * (metrics.densityDpi/160f);
return px;
}
只需根据您的要求调用您想要的任何方法即可。
关于Canvas 上的 Android 文本大小与 TextView 中的文本大小不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16103344/