您需要通过DisplayMetrics或其他方式获取屏幕宽度...
要获取字符大小,请使用带有边界的paint进行计算。
characterWidth/screenWidth = characterScreenPercentage
我将其设为double,但您可以轻松更改为float。
对于字符:
public Double characterToScreenWidthPercentage(Character c) {
Paint paint = new Paint();
Rect boundA = new Rect();
DisplayMetrics metrics = new DisplayMetrics();
((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay().getMetrics(metrics);
paint.getTextBounds(Character.toString(c), 0, 1, boundA);
Log.v("fn", Integer.toString(boundA.width()));
Log.v("fn", Integer.toString(metrics.widthPixels));
Log.v("fn", Double.toString((float) boundA.width() / (float) metrics.widthPixels));
return ((double) boundA.width() / (double) metrics.widthPixels);
}
对于字符串:
public Double stringToScreenWidthPercentage(String str) {
Paint paint = new Paint();
Rect boundA = new Rect();
DisplayMetrics metrics = new DisplayMetrics();
((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay().getMetrics(metrics);
paint.getTextBounds(str, 0, 1, boundA);
Log.v("fn", Integer.toString(boundA.width()));
Log.v("fn", Integer.toString(metrics.widthPixels));
Log.v("fn", Double.toString((float) boundA.width() / (float) metrics.widthPixels));
return ((double) boundA.width() / (double) metrics.widthPixels);
}
getWindowManager().getDefaultDisplay().getMetrics(metrics)
计算屏幕宽度并将测量的文本宽度除以它吗?(关于您自己提到的问题,只需根据屏幕上“dp”的宽度设置字体大小等即可。) - Konstantin Loginov