您将需要通过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);
}