Android 上如何获取字符串宽度?

发布于 2024-09-16 23:01:38 字数 19 浏览 2 评论 0 原文

如果可以的话我也想长高。

I would like to get height too if possible.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

潇烟暮雨 2024-09-23 23:01:38

您可以使用 Paint 对象的 getTextBounds(String text, int start, int end, 矩形边界) 方法。您可以使用 TextView 提供的绘制对象,也可以根据您想要的文本外观自行构建一个绘制对象。

使用 Textview 您可以执行以下操作:

Rect bounds = new Rect();
Paint textPaint = textView.getPaint();
textPaint.getTextBounds(text, 0, text.length(), bounds);
int height = bounds.height();
int width = bounds.width();

You can use the getTextBounds(String text, int start, int end, Rect bounds) method of a Paint object. You can either use the paint object supplied by a TextView or build one yourself with your desired text appearance.

Using a Textview you Can do the following:

Rect bounds = new Rect();
Paint textPaint = textView.getPaint();
textPaint.getTextBounds(text, 0, text.length(), bounds);
int height = bounds.height();
int width = bounds.width();
好久不见√ 2024-09-23 23:01:38

如果您只需要宽度,可以使用:

float width = paint.measureText(string);

http://developer.android.com/reference/android/graphics/Paint.html#measureText(java.lang.String)

If you just need the width you can use:

float width = paint.measureText(string);

http://developer.android.com/reference/android/graphics/Paint.html#measureText(java.lang.String)

最美的太阳 2024-09-23 23:01:38

文本有两种不同的宽度度量。一是在宽度上绘制的像素数,另一个是绘制文本后光标应前进的“像素”数。

paint.measureTextpaint.getTextWidths 返回绘制给定字符串后光标应前进的像素数(以浮点形式表示)。对于绘制的像素数,请使用其他答案中提到的paint.getTextBounds。我相信这被称为字体的“高级”。

对于某些字体,这两个测量值不同(很多),例如字体 Black Chancery 的字母超出了另一个字体字母(重叠)- 请参阅大写“L”。使用其他答案中提到的 paint.getTextBounds 来绘制像素。

There are two different width measures for a text. One is the number of pixels which has been drawn in the width, the other is the number of 'pixels' the cursor should be advanced after drawing the text.

paint.measureText and paint.getTextWidths returns the number of pixels (in float) which the cursor should be advanced after drawing the given string. For the number of pixels painted use paint.getTextBounds as mentioned in other answer. I believe this is called the 'Advance' of the font.

For some fonts these two measurements differ (alot), for instance the font Black Chancery have letters which extend past the other letters (overlapping) - see the capital 'L'. Use paint.getTextBounds as mentioned in other answer to get pixels painted.

不必你懂 2024-09-23 23:01:38

我用这种方式测量了宽度:

String str ="Hiren Patel";

Paint paint = new Paint();
paint.setTextSize(20);
Typeface typeface = Typeface.createFromAsset(getAssets(), "Helvetica.ttf");
paint.setTypeface(typeface);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL);
Rect result = new Rect();
paint.getTextBounds(str, 0, str.length(), result);

Log.i("Text dimensions", "Width: "+result.width());

这会对你有帮助。

I have measured width in this way:

String str ="Hiren Patel";

Paint paint = new Paint();
paint.setTextSize(20);
Typeface typeface = Typeface.createFromAsset(getAssets(), "Helvetica.ttf");
paint.setTypeface(typeface);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL);
Rect result = new Rect();
paint.getTextBounds(str, 0, str.length(), result);

Log.i("Text dimensions", "Width: "+result.width());

This would help you.

此刻的回忆 2024-09-23 23:01:38

您很可能想知道具有给定字体的给定文本字符串的绘制尺寸(即特定的 字体,例如具有 BOLD_ITALIC 样式的“sans-serif”字体系列,以及特定尺寸(以 sp 或 px 为单位)。

您可以进入较低级别并使用 TextView "noreferrer">Paint 对象直接用于单行文本,例如:

// Maybe you want to construct a (possibly static) member for repeated computations
Paint paint = new Paint();

// You can load a font family from an asset, and then pick a specific style:
//Typeface plain = Typeface.createFromAsset(assetManager, pathToFont); 
//Typeface bold = Typeface.create(plain, Typeface.DEFAULT_BOLD);
// Or just reference a system font:
paint.setTypeface(Typeface.create("sans-serif",Typeface.BOLD));

// Don't forget to specify your target font size. You can load from a resource:
//float scaledSizeInPixels = context.getResources().getDimensionPixelSize(R.dimen.mediumFontSize);
// Or just compute it fully in code:
int spSize = 18;
float scaledSizeInPixels = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_SP,
            spSize,
            context.getResources().getDisplayMetrics());
paint.setTextSize(scaledSizeInPixels);

// Now compute!
Rect bounds = new Rect();
String myString = "Some string to measure";
paint.getTextBounds(myString, 0, myString.length(), bounds);
Log.d(TAG, "width: " + bounds.width() + " height: " + bounds.height());

对于多行或跨行文本 (< code>SpannedString),请考虑使用 StaticLayout,在其中提供宽度并导出高度。有关在自定义视图中测量文本并将文本绘制到画布上的详细答案,请参阅:https://stackoverflow.com/ a/41779935/954643

另外值得注意的是 @arberg 下面关于绘制的像素与前进宽度的回复(“绘制给定字符串后光标应前进的像素数(以浮点数表示)”),以防万一需要处理这个问题。

Most likely you want to know the painted dimensions for a given string of text with a given font (i.e. a particular Typeface such as the “sans-serif” font family with a BOLD_ITALIC style, and particular size in sp or px).

Rather than inflating a full-blown TextView, you can go lower level and work with a Paint object directly for single-line text, for example:

// Maybe you want to construct a (possibly static) member for repeated computations
Paint paint = new Paint();

// You can load a font family from an asset, and then pick a specific style:
//Typeface plain = Typeface.createFromAsset(assetManager, pathToFont); 
//Typeface bold = Typeface.create(plain, Typeface.DEFAULT_BOLD);
// Or just reference a system font:
paint.setTypeface(Typeface.create("sans-serif",Typeface.BOLD));

// Don't forget to specify your target font size. You can load from a resource:
//float scaledSizeInPixels = context.getResources().getDimensionPixelSize(R.dimen.mediumFontSize);
// Or just compute it fully in code:
int spSize = 18;
float scaledSizeInPixels = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_SP,
            spSize,
            context.getResources().getDisplayMetrics());
paint.setTextSize(scaledSizeInPixels);

// Now compute!
Rect bounds = new Rect();
String myString = "Some string to measure";
paint.getTextBounds(myString, 0, myString.length(), bounds);
Log.d(TAG, "width: " + bounds.width() + " height: " + bounds.height());



For multi-line or spanned text (SpannedString), consider using a StaticLayout, in which you provide the width and derive the height. For 
a very elaborate answer on measuring and drawing text to a canvas in a custom view doing that, see: https://stackoverflow.com/a/41779935/954643

Also worth noting @arberg's reply below about the pixels painted vs the advance width ("number of pixels (in float) which the cursor should be advanced after drawing the given string"), in case you need to deal with that.

青春如此纠结 2024-09-23 23:01:38

我想分享一种更好的方法(比当前接受的答案更通用)使用静态类获取绘制文本(String)的精确宽度StaticLayout

StaticLayout.getDesiredWidth(text, textPaint))

此方法比 textView.getTextBounds() 更准确,因为您可以计算多行 TextView 中单行的宽度,或者您可能不会一开始就使用 TextView(例如在自定义 View 实现中)。

这种方式与 textPaint.measureText(text) 类似,但在极少数情况下似乎更准确。

I'd like to share a better way (more versatile then the current accepted answer) of getting the exact width of a drawn text (String) with the use of static class StaticLayout:

StaticLayout.getDesiredWidth(text, textPaint))

this method is more accurate than textView.getTextBounds(), since you can calculate width of a single line in a multiline TextView, or you might not use TextView to begin with (for example in a custom View implementation).

This way is similar to textPaint.measureText(text), however it seems to be more accurate in rare cases.

面犯桃花 2024-09-23 23:01:38

simplay 我在行中添加最大字符并用最大空间挑战它并创建新行

    v_y = v_y + 30;
    String tx = "مبلغ وقدرة : "+ AmountChar+" لا غير";

    myPaint.setTextAlign(Paint.Align.RIGHT);

    int pxx = 400;
    int pxy = v_y ;
    int word_no = 1;
    int word_lng = 0;
    int max_word_lng = 45;
    int new_line = 0;
    int txt_lng = tx.length();
    int words_lng =0;
    String word_in_line = "" ;
    for (String line : tx.split(" "))
    {
        word_lng = line.length() ;
        words_lng += line.length() + 1;

        if (word_no == 1 )
        {word_in_line = line;
        word_no += 1;
        }
        else
            { word_in_line += " " + line;
            word_no += 1;
            }

        if (word_in_line.length() >= max_word_lng)
       {
           canvas.drawText(word_in_line, pxx, pxy, myPaint);
            new_line += 1;
            pxy = pxy + 30;
            word_no = 1;
            word_in_line = "";
        }
        if (txt_lng <= words_lng )
        { canvas.drawText(word_in_line, pxx, pxy, myPaint); }
    }

    v_y = pxy;

simplay i tack max charcter in the line and defieded it with max space and create new line

    v_y = v_y + 30;
    String tx = "مبلغ وقدرة : "+ AmountChar+" لا غير";

    myPaint.setTextAlign(Paint.Align.RIGHT);

    int pxx = 400;
    int pxy = v_y ;
    int word_no = 1;
    int word_lng = 0;
    int max_word_lng = 45;
    int new_line = 0;
    int txt_lng = tx.length();
    int words_lng =0;
    String word_in_line = "" ;
    for (String line : tx.split(" "))
    {
        word_lng = line.length() ;
        words_lng += line.length() + 1;

        if (word_no == 1 )
        {word_in_line = line;
        word_no += 1;
        }
        else
            { word_in_line += " " + line;
            word_no += 1;
            }

        if (word_in_line.length() >= max_word_lng)
       {
           canvas.drawText(word_in_line, pxx, pxy, myPaint);
            new_line += 1;
            pxy = pxy + 30;
            word_no = 1;
            word_in_line = "";
        }
        if (txt_lng <= words_lng )
        { canvas.drawText(word_in_line, pxx, pxy, myPaint); }
    }

    v_y = pxy;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文