您将需要通过 DisplayMetrics 或如何获得屏幕宽度......
要获取字符大小,请使用带有边界的绘制来计算。
characterWidth/screenWidth = characterScreenPercentage
我把它做成了双倍,但你可以很容易地把它改成浮点数。
对于字符:
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);
}