Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
android中获取文本宽度的最有效方法是什么?_Android - Fatal编程技术网

android中获取文本宽度的最有效方法是什么?

android中获取文本宽度的最有效方法是什么?,android,Android,我需要检测适合的文本的最大文本大小(宽度、高度)。获取文本大小值的最快方法是什么 我尝试在for循环中迭代文本大小,并获取Paint.getTextBounds(),但这需要很多时间,整个调用只需几秒钟。绘画字体是字体。字符宽度相等时,MONOSPACE将有助于节省时间。文本大小和字符宽度之间是否存在依赖关系以避免调用Paint.getTextBounds()?这项任务非常类似于为“匹配父项”的TextView获取文本大小,所以有人知道如何快速完成吗?因为您使用的是字体。MONOSPACE,您不

我需要检测适合的文本的最大文本大小(宽度、高度)。获取文本大小值的最快方法是什么


我尝试在for循环中迭代文本大小,并获取
Paint.getTextBounds()
,但这需要很多时间,整个调用只需几秒钟。绘画字体是
字体。字符宽度相等时,MONOSPACE
将有助于节省时间。文本大小和字符宽度之间是否存在依赖关系以避免调用
Paint.getTextBounds()
?这项任务非常类似于为“匹配父项”的TextView获取文本大小,所以有人知道如何快速完成吗?

因为您使用的是
字体。MONOSPACE
,您不必为每个字符或每个文本大小计算文本边界

假设您有变量
paint
,它的文本大小设置为12作为开始。您想用文本填充区域
宽度
高度
。现在

Rect initialBounds = new Rect();
paint.getTextBounds(" ", 0, 1, initialBounds);
float initialTextSize = 12, increase = 2, currentSize = 12;
int charCount = text.length();//the char count we want to print
int maxCharCount = 0;//max count of chars we can print at currentSize.
do{
    currentSize += increase;
    float charWidth = initialBounds.right * currentSize / initialTextSize;
    float charHeight = initialBounds.bottom * currentSize / initialTextSize;
    int charPerLine = width / charWidth;
    int lineCount = height / charHeight;
    maxCharCount = charPerLine * lineCount;
}
while(maxCharCount > charCount);
currentSize -= increase;//this is the size we are looking for.
之后,您可以调用
paint.setTextSize(currentSize)并绘制文本


我没有测试代码,但它应该可以工作。如果您想在必要时将文本大小减小到初始文本大小以下,则需要进行一些修改。

我不确定,但是Paint.getTextBounds()可能不考虑Typeface.MONOSPACE。您不能只计算lets(比如空格字符)的边界,并使用该值计算可以放入该区域的字符数,而不是重复调用Paint.getTextBounds()?是的,当然可以。但是我应该迭代文本大小来计算每个文本大小的总行宽,这需要花费太多的时间。您确定文本大小和宽度之间是线性依赖关系,因此可以只使用
initialBounds.right*currentSize/initialTextSize
?如果这是真的,那么只需将最大文本大小计算为
final_text_size=max_width/cur_width*cur_text_size
,而无需迭代