根据宽度文本面积计算文本大小 [英] Calculate text size according to width of text area

查看:146
本文介绍了根据宽度文本面积计算文本大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有应设置的TextView与指定宽度的文本。它需要计算文字的大小,以适应它到TextView的。

I have a text that should be set to TextView with specified width. It needs to calculate the text size to fit it into TextView.

在换句话说:有没有办法使文本符合T​​extView的区域,像ImageView的规模型功能

In other words: Is there a way to fit text into TextView area, like the ImageView scale type feature?

推荐答案

如果它是空间的大小的文本需要你的后那么下面可能会有所帮助:

If it is the Size of the space the Text takes your after then the following might help:

Paint paint = new Paint();
Rect bounds = new Rect();

int text_height = 0;
int text_width = 0;

paint.setTypeface(Typeface.DEFAULT);// your preference here
paint.setTextSize(25);// have this the same as your text size

String text = "Some random text";

paint.getTextBounds(text, 0, text.length(), bounds);

text_height =  bounds.height();
text_width =  bounds.width();

编辑(评论后): 使用上述相反的:

Edit (after comment): Use the above in reverse:

int text_height = 50;
int text_width = 200;

int text_check_w = 0;
int text_check_h = 0;

int incr_text_size = 1;
boolean found_desired_size = true;

while (found_desired_size){
    paint.setTextSize(incr_text_size);// have this the same as your text size

    String text = "Some random text";

    paint.getTextBounds(text, 0, text.length(), bounds);

    text_check_h =  bounds.height();
    text_check_w =  bounds.width();
    incr_text_size++;

if (text_height == text_check_h && text_width == text_check_w){
found_desired_size = false;
}
}
return incr_text_size; // this will be desired text size from bounds you already have

//此方法可以进行调整了一下,但给你的,是你可以做的想法

//this method may be tweaked a bit, but gives you an idea on what you can do

这篇关于根据宽度文本面积计算文本大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆