gpt4 book ai didi

android - 在android中获取文本宽度的最有效方法?

转载 作者:太空狗 更新时间:2023-10-29 15:04:02 26 4
gpt4 key购买 nike

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

我尝试在 for 循环中迭代文本大小并获取 Paint.getTextBounds() 但它需要花费大量时间并且整个调用需要几秒钟。绘画字体是 Typeface.MONOSPACE 这应该有助于节省时间,因为字符宽度是相等的。文本大小和字符宽度之间是否存在任何依赖关系以避免调用 Paint.getTextBounds() ?该任务与为 match_parent 宽度和高度获取 TextView 的文本大小非常相似,所以有人知道如何快速完成吗?

最佳答案

因为您使用 Typeface.MONOSPACE,所以您不必为每个字符或每个文本大小计算文本边界。

假设您有变量 paint,开始时文本大小设置为 12。您想要用文本填充区域 widthheight。现在

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); 并绘制文本即可。

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

关于android - 在android中获取文本宽度的最有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23596499/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com