java 如何以像素为单位计算字符串字体宽度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6360089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:33:41  来源:igfitidea点击:

How to calculate string font width in pixels?

javaandroid

提问by Balaji Khadake

I want to calculate string font width in pixels in android. I am having string array and I am appending all these array elements to form one string. so I have to set fixed spacing in between two consecutive array element.i am placing this final string into textview. Finally I am adding this textview to tablerow. In short i want to view table structure with title and values. I have seen many post over here but not getting solution for this.

我想在android 中以像素为单位计算字符串字体宽度。我有字符串数组,我将所有这些数组元素附加到一个字符串中。所以我必须在两个连续的数组元素之间设置固定间距。我将这个最终字符串放入 textview。最后,我将此文本视图添加到 tablerow。简而言之,我想查看带有标题和值的表结构。我在这里看到了很多帖子,但没有得到解决方案。

Thanks in advance...!!!

提前致谢...!!!

回答by Jake Basile

Looks like there is a measureTextmethod available on Paint. I also found an example:

看起来有一种measureText方法可用Paint。我还找到了一个例子

mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(5);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setTextSize(64);
mPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.ITALIC));
// ...
float w = mPaint.measureText(text, 0, text.length());

回答by Voy

Thanks Jake for the working solution, yet I found this to work for me too:

感谢Hyman的工作解决方案,但我发现这对我也有用:

someText = "Lorem Ipsum";
TextView myTextView = (TextView) findViewById(R.id.myTextView);
float w = myTextView.getPaint().measureText(someText);

Getting the Paint directly from the TextView that I'm going to work with makes me feel that the anwser will be more accurate.

直接从我将要使用的 TextView 获取 Paint 让我觉得 anwser 会更准确。

回答by pavul

I don't know if this works, but it can.

我不知道这是否有效,但可以。

int textSize=20;
Paint p=new Paint();
p.setTextSize(textSize);
String string="Hello im a string.";
public int getStringWidt()
{
    return string.length*textSize;
}