我有一个文本应该设置为具有指定宽度的TextView.它需要计算文本大小以使其适合TextView.
换句话说:有没有办法将文本放入TextView区域,比如ImageView缩放类型功能?
Ham*_*boh 30
这应该是一个简单的解决方案:
public void correctWidth(TextView textView, int desiredWidth)
{
Paint paint = new Paint();
Rect bounds = new Rect();
paint.setTypeface(textView.getTypeface());
float textSize = textView.getTextSize();
paint.setTextSize(textSize);
String text = textView.getText().toString();
paint.getTextBounds(text, 0, text.length(), bounds);
while (bounds.width() > desiredWidth)
{
textSize--;
paint.setTextSize(textSize);
paint.getTextBounds(text, 0, text.length(), bounds);
}
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*per 29
如果它是文本占用你的空间的大小,那么以下可能会有所帮助:
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();
Run Code Online (Sandbox Code Playgroud)
编辑(评论后):反过来使用上面的内容:
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
Run Code Online (Sandbox Code Playgroud)
//这个方法可能会稍微调整一下,但会让你知道你能做些什么
sel*_*guo 11
public static float getFitTextSize(TextPaint paint, float width, String text) {
float nowWidth = paint.measureText(text);
float newSize = (float) width / nowWidth * paint.getTextSize();
return newSize;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
40308 次 |
| 最近记录: |