Estoy tratando de crear un método para cambiar el tamaño del texto de varias líneas en un TextView
de manera que quepa dentro de los límites (las dimensiones X e Y) del TextView
.¿Cómo escalar/cambiar el tamaño del texto para que se ajuste a un TextView?
En este momento, tengo algo, pero todo lo que hace es cambiar el tamaño del texto de manera que solo la primera letra/carácter del texto llene las dimensiones del TextView
(es decir, solo la primera letra es visible y es enorme). Necesito que se ajuste a todas las líneas del texto dentro de los límites de TextView.
Esto es lo que tengo hasta ahora:
public static void autoScaleTextViewTextToHeight(TextView tv)
{
final float initSize = tv.getTextSize();
//get the width of the view's back image (unscaled)....
float minViewHeight;
if(tv.getBackground()!=null)
{
minViewHeight = tv.getBackground().getIntrinsicHeight();
}
else
{
minViewHeight = 10f;//some min.
}
final float maxViewHeight = tv.getHeight() - (tv.getPaddingBottom()+tv.getPaddingTop())-12;// -12 just to be sure
final String s = tv.getText().toString();
//System.out.println(""+tv.getPaddingTop()+"/"+tv.getPaddingBottom());
if(minViewHeight >0 && maxViewHeight >2)
{
Rect currentBounds = new Rect();
tv.getPaint().getTextBounds(s, 0, s.length(), currentBounds);
//System.out.println(""+initSize);
//System.out.println(""+maxViewHeight);
//System.out.println(""+(currentBounds.height()));
float resultingSize = 1;
while(currentBounds.height() < maxViewHeight)
{
resultingSize ++;
tv.setTextSize(resultingSize);
tv.getPaint().getTextBounds(s, 0, s.length(), currentBounds);
//System.out.println(""+(currentBounds.height()+tv.getPaddingBottom()+tv.getPaddingTop()));
//System.out.println("Resulting: "+resultingSize);
}
if(currentBounds.height()>=maxViewHeight)
{
//just to be sure, reduce the value
tv.setTextSize(resultingSize-1);
}
}
}
Creo que el problema está en el uso de tv.getPaint().getTextBounds(...)
. Siempre devuelve números pequeños para los límites de texto ... pequeños en relación con los valores tv.getWidth()
y tv.getHeight()
... incluso si el tamaño del texto es muy superior al ancho o alto del TextView
.
Posible duplicado de: http://stackoverflow.com/a/7875656/435605 –
posible duplicado de [Texto Auto Escala Vista de Texto para caber dentro de los límites] (http://stackoverflow.com/preguntas/5033012/auto-escala-TextView de texto a-fit-dentro-fuera) –
Esta solución es ordenada: [texto escala en una vista para encajar?] [1] [1]: http://stackoverflow.com/a/7259136/3857562 –