Подтвердить что ты не робот

Рассчитать размер текста в соответствии с шириной области текста

У меня есть текст, который должен быть установлен в TextView с указанной шириной. Он должен вычислить размер текста, чтобы он поместился в TextView.

Другими словами: есть ли способ подгонки текста в область TextView, например, функция типа масштабирования ImageView?

4b9b3361

Ответ 1

Если это размер пространства, в котором текст принимает ваш, то следующее может помочь:

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

Изменить (после комментария): Используйте вышеописанное в обратном порядке:

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

//этот метод может быть немного изменен, но дает вам представление о том, что вы можете сделать

Ответ 2

Это должно быть простым решением:

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

Ответ 3

 public static float getFitTextSize(TextPaint paint, float width, String text) {
     float nowWidth = paint.measureText(text);
     float newSize = (float) width / nowWidth * paint.getTextSize();
     return newSize;
 }

Ответ 4

Мне также пришлось столкнуться с такой же проблемой, когда я должен был убедиться, что текст вписывается в конкретную рамку. Следующее - самое эффективное и наиболее точное решение, которое у меня есть на данный момент:

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

Это просто вычисляет правильный размер, а не запускает пробный/пробный тест.

Вы можете использовать его следующим образом:

float availableWidth = ...; // use your text view width, or any other width.
String text = "Hi there";
TextPaint paint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
paint.setTypeface(...);
paint.calibrateTextSize(text, availableWidth);

Или иначе, без дополнительного типа:

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

Используйте так:

float availableWidth = ...; // use your text view 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);

Ответ 5

Мне нужен был тот, который рассчитывает наилучшее соответствие для ширины и высоты в пикселях. Это мое решение:

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