使用等宽字体估计单行TextView中的字符

时间:2014-09-06 04:34:11

标签: android fonts

我试图估算TextView中我可以放在一行中的字符数。我们的想法是获得显示宽度,然后将其除以字符的宽度。 (我使用显示宽度,因为看起来所有获取视图宽度的方法都被破坏了。)

以下是TextView

<TextView
    android:id="@+id/lblNumbers"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:textAppearance="?android:attr/textAppearanceLarge" />

onCreate

期间
final TextView lblNumbers = (TextView) findViewById(R.id.lblNumbers);
if (lblNumbers != null) {
    lblNumbers.setTypeface(Typeface.MONOSPACE);
}

我希望monospace字体应该能够轻松(或更容易)。

我可以检索Typeface,但我似乎找不到任何获取文字指标的方法:

final TextView lblNumbers = (TextView) findViewById(R.id.lblNumbers);
if (lblNumbers != null) {
    Typeface tf = lblNumbers.getTypeface();
}

如何使用TextView字体确定monospace中使用的字符的宽度?

1 个答案:

答案 0 :(得分:0)

迈克是对的 - TextPaint对象中提供了相关信息。

Float pixelWidth = 1.0f;
DisplayMetrics dm = getBaseContext().getResources().getDisplayMetrics();
if (dm != null) {
    pixelWidth = (float) dm.widthPixels;
    Log.d("PRNG", "Display width: " + pixelWidth.toString());
}

Float charWidth = 1.0f;
TextView lblNumbers = (TextView) findViewById(R.id.lblNumbers);
if (lblNumbers != null) {
    charWidth = lblNumbers.getPaint().measureText(" ");
    Log.d("PRNG", "Text width: " + charWidth.toString());
}

/* The extra gyrations negate Math.round's rounding up */
int charPerLine = Math.round(pixelWidth - 0.5f) / Math.round(charWidth - 0.5f);