如何将文本宽度(以像素为单位)转换为屏幕宽度/高度的百分比?

2024-04-05

我正在测量字符串文本,看看是否应该添加\n用于包装。

我正在使用Paint.measureText函数,并且它在大多数情况下都有效,但我发现这是不准确的,因为 px 不等于 dp - 我在网上看到了如何将像素转换为 dp,但我宁愿做的是例如,将 px 转换为屏幕尺寸的百分比

If a是 8 像素宽,我怎么说:

float LetterWidthPercent = _______ //get width of character in percent of screen width
float LetterHeightPercent = _______ //get height of character in percent of screen height

这样我就可以看到:

 if (LineOfTextWidth >= ScreenWidth * 0.9f) //90%

这将是一个非常有用的功能。


您需要通过 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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将文本宽度(以像素为单位)转换为屏幕宽度/高度的百分比? 的相关文章

随机推荐