您需要通过 DisplayMetrics 或其他方式获取屏幕宽度...
为了获取字符大小,请使用带有边界的 Paint 来计算。
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);
}