Pregunta

¿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 use la longitud para el ajuste de palabras.

¿Fue útil?

Solución

Si solo quiere 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 tiene una variable Graphics llamada g , usaría:

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

Para otros kits de herramientas, deberá proporcionarnos más información; siempre dependerá del kit de herramientas.

Otros consejos

No siempre necesita ser dependiente del kit de herramientas o uno no siempre necesita 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.

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

}

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

Espero que le ahorre tiempo a otro tipo que quiera 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;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top