【问题标题】:getTextBounds returning wrong valuesgetTextBounds 返回错误的值
【发布时间】:2014-08-14 23:19:19
【问题描述】:

我正在尝试获取文本字符串的宽度(以像素为单位),我得到的值为 8,这不会产生影响,因为这意味着每个字母的宽度为 1 个像素。 我有以下代码

Rect bounds = new Rect();
Paint paint = new Paint();
paint.setTextSize(12);
paint.getTextBounds("ABCDEFGHI", 0, 1, bounds);
width=bounds.right;      // this value is 8

bounds 的值为 0,0,8,9

【问题讨论】:

标签: android


【解决方案1】:

该方法采用以下参数:

getTextBounds(char[] text, int index, int count, Rect bounds)

而且你只要求一个字符的宽度(第三个参数),而不是整个字符串:

paint.getTextBounds("ABCDEFGHI", 0, 1, bounds);

bounds.right为8,即字母A的宽度。

在您的情况下,正确的调用是:

String str = "ABCDEFGHI";
paint.getTextBounds(str, 0, str.length(), bounds);

【讨论】:

    【解决方案2】:

    您可以尝试使用以下代码获取文本的宽度(以像素为单位)(来自Android: measureText() Return Pixels Based on Scaled Pixels):

    final float densityMultiplier = getContext().getResources().getDisplayMetrics().density;
    final float scaledPx = 12 * densityMultiplier;
    paint.setTextSize(scaledPx);
    final float size = paint.measureText("ABCDEFGHI");
    

    size 应该是您的宽度(以像素为单位)。

    【讨论】:

      猜你喜欢
      • 2015-06-19
      • 2019-02-03
      • 2014-01-16
      • 2021-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多