web-dev-qa-db-fra.com

Calculez la taille du texte en fonction de la largeur de la zone de texte

J'ai un texte qui doit être défini sur TextView avec une largeur spécifiée. Il doit calculer la taille du texte pour l'adapter à TextView.

En d'autres termes: existe-t-il un moyen d'ajuster le texte dans la zone TextView, comme la fonction de type d'échelle ImageView?

29
kankan

S'il s'agit de la taille de l'espace utilisé par le texte, les éléments suivants peuvent vous aider:

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 (après commentaire): Utilisez ce qui précède à l'envers:

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

// cette méthode peut être légèrement modifiée, mais vous donne une idée de ce que vous pouvez faire

29

Cela devrait être une solution simple:

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);
}
29
Hamzeh Soboh
 public static float getFitTextSize(TextPaint Paint, float width, String text) {
     float nowWidth = Paint.measureText(text);
     float newSize = (float) width / nowWidth * Paint.getTextSize();
     return newSize;
 }
11
selevenguo

J'ai également dû faire face au même problème lorsque je devais m'assurer que le texte s'inscrit dans une boîte spécifique. Ce qui suit est la solution la plus performante et la plus précise que j'ai pour le moment:

/**
 * 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));
    }
}

Cela calcule simplement la taille correcte plutôt que d'exécuter un test d'essai/d'erreur.

Vous pouvez l'utiliser comme ceci:

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);

Ou sinon, sans le type supplémentaire:

/**
 * 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));
}

Utilisez comme ça:

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);
3
Ben Barkay

J'en avais besoin d'un qui calcule le meilleur ajustement pour la largeur et la hauteur, en pixels. Voici ma solution:

private static int getFitTextSize(Paint paint, int width, int height, String text) {
   int maxSizeToFitWidth = (int)((float)width / Paint.measureText(text) * Paint.getTextSize());
   return Math.min(maxSizeToFitWidth, height);
}
1
FreddaP