Calcular el ancho de visualización de una cadena en Java


Cómo calcular la longitud (en píxeles) de una cadena en Java?

Preferible sin usar Swing.

EDITAR: Me gustaría dibujar la cadena usando drawString () en Java2D y usa la longitud para envolver palabras.

Author: eflles, 2008-11-03

4 answers

Si solo desea usar AWT, use Graphics.getFontMetrics (opcionalmente especificando la fuente, para una no predeterminada) para obtener un FontMetrics y luego FontMetrics.stringWidth para encontrar el ancho de la cadena especificada.

Por ejemplo, si tienes una variable Graphics llamada g, usarías:

int width = g.getFontMetrics().stringWidth(text);

Para otros conjuntos de herramientas, tendrá que darnos más información - siempre va a depender del conjunto de herramientas.

 111
Author: Jon Skeet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-02 05:28:46

No siempre es necesario que dependa del kit de herramientas o no siempre es necesario usar el enfoque FontMetrics, ya que requiere obtener primero un objeto gráfico que está ausente en un contenedor web o en un entorno sin cabeza.

He probado esto en un servlet web y calcula el ancho del texto.

import java.awt.Font;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;

...

String text = "Hello World";
AffineTransform affinetransform = new AffineTransform();     
FontRenderContext frc = new FontRenderContext(affinetransform,true,true);     
Font font = new Font("Tahoma", Font.PLAIN, 12);
int textwidth = (int)(font.getStringBounds(text, frc).getWidth());
int textheight = (int)(font.getStringBounds(text, frc).getHeight());

Agregue los valores necesarios a estas dimensiones para crear cualquier margen requerido.

 42
Author: Olofu Mark,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-22 22:35:20

Utilice el método getWidth en la siguiente clase:

import java.awt.*;
import java.awt.geom.*;
import java.awt.font.*;

class StringMetrics {

  Font font;
  FontRenderContext context;

  public StringMetrics(Graphics2D g2) {

    font = g2.getFont();
    context = g2.getFontRenderContext();
  }

  Rectangle2D getBounds(String message) {

    return font.getStringBounds(message, context);
  }

  double getWidth(String message) {

    Rectangle2D bounds = getBounds(message);
    return bounds.getWidth();
  }

  double getHeight(String message) {

    Rectangle2D bounds = getBounds(message);
    return bounds.getHeight();
  }

}
 7
Author: Ed Poor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-26 18:41:22

Personalmente estaba buscando algo que me permitiera calcular el área de cadena multilínea, para poder determinar si el área dada es lo suficientemente grande como para imprimir la cadena, conservando una fuente específica.

Espero que sea seguro algún tiempo para otro tipo que pueda querer hacer un trabajo similar en Java, así que solo quería compartir la solución:

private static Hashtable hash = new Hashtable();
private Font font;
private LineBreakMeasurer lineBreakMeasurer;
private int start, end;

public PixelLengthCheck(Font font) {
    this.font = font;
}

public boolean tryIfStringFits(String textToMeasure, Dimension areaToFit) {
    AttributedString attributedString = new AttributedString(textToMeasure, hash);
    attributedString.addAttribute(TextAttribute.FONT, font);
    AttributedCharacterIterator attributedCharacterIterator =
            attributedString.getIterator();
    start = attributedCharacterIterator.getBeginIndex();
    end = attributedCharacterIterator.getEndIndex();

    lineBreakMeasurer = new LineBreakMeasurer(attributedCharacterIterator,
            new FontRenderContext(null, false, false));

    float width = (float) areaToFit.width;
    float height = 0;
    lineBreakMeasurer.setPosition(start);

    while (lineBreakMeasurer.getPosition() < end) {
        TextLayout textLayout = lineBreakMeasurer.nextLayout(width);
        height += textLayout.getAscent();
        height += textLayout.getDescent() + textLayout.getLeading();
    }

    boolean res = height <= areaToFit.getHeight();

    return res;
}
 0
Author: wmioduszewski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-25 12:10:31