También tuve que enfrentar el mismo problema al tener que asegurarme de que el texto encaje en una caja específica. El siguiente es el mejor rendimiento y la solución más precisa que tengo para ello en la actualidad
/**
* A paint that has utilities dealing with painting text.
* @author <a href="maillto:nospam">Ben Barkay</a>
* @version 10, Aug 2014
*/
public class TextPaint extends android.text.TextPaint {
/**
* Constructs a new {@code TextPaint}.
*/
public TextPaint() {
super();
}
/**
* Constructs a new {@code TextPaint} using the specified flags
* @param flags
*/
public TextPaint(int flags) {
super(flags);
}
/**
* Creates a new {@code TextPaint} copying the specified {@code source} state.
* @param source The source paint to copy state from.
*/
public TextPaint(Paint source) {
super(source);
}
// Some more utility methods...
/**
* Calibrates this paint's text-size to fit the specified text within the specified width.
* @param text The text to calibrate for.
* @param boxWidth The width of the space in which the text has to fit.
*/
public void calibrateTextSize(String text, float boxWidth) {
calibrateTextSize(text, 0, Float.MAX_VALUE, boxWidth);
}
/**
* Calibrates this paint's text-size to fit the specified text within the specified width.
* @param text The text to calibrate for.
* @param min The minimum text size to use.
* @param max The maximum text size to use.
* @param boxWidth The width of the space in which the text has to fit.
*/
public void calibrateTextSize(String text, float min, float max, float boxWidth) {
setTextSize(10);
setTextSize(Math.max(Math.min((boxWidth/measureText(text))*10, max), min));
}
}
Esto simplemente calcula el tamaño correcto en lugar de ejecutar una prueba de ensayo/error.
Se puede utilizar la siguiente manera:
float availableWidth = ...; // use your text view's width, or any other width.
String text = "Hi there";
TextPaint paint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
paint.setTypeface(...);
paint.calibrateTextSize(text, availableWidth);
O de lo contrario, si se quiere entregar la basura:
/**
* Calibrates this paint's text-size to fit the specified text within the specified width.
* @param paint The paint to calibrate.
* @param text The text to calibrate for.
* @param min The minimum text size to use.
* @param max The maximum text size to use.
* @param boxWidth The width of the space in which the text has to fit.
*/
public static void calibrateTextSize(Paint paint, String text, float min, float max, float boxWidth) {
paint.setTextSize(10);
paint.setTextSize(Math.max(Math.min((boxWidth/paint.measureText(text))*10, max), min));
}
uso de este modo:
float availableWidth = ...; // use your text view's width, or any other width.
String text = "Hi there";
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setTypeface(...);
calibrateTextSize(paint, text, 0, Float.MAX_VALUE, availableWidth);
Marque esta respuesta aquí http://stackoverflow.com/questions/7259016/scale-text-in-a-view-to-fit/7259136#7259136 – Ronnie