使用单空格字体估计TextView单行中的字符数



我正在尝试估计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();
}

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

Mike是对的-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);

最新更新