Pergunta

Como calcular o comprimento (em pixels) de uma string em Java?

Preferível sem usar Swing.

EDIT: Eu gostaria de chamar a string usando o cordão () em Java2D e usar o comprimento de quebra de linha.

Foi útil?

Solução

Se você só quer usar AWT, então use Graphics.getFontMetrics (opcionalmente especificando o tipo de letra, para um não-padrão) para obter uma FontMetrics e, em seguida, FontMetrics.stringWidth para encontrar a largura para a cadeia especificada.

Por exemplo, se você tem uma variável Graphics chamado g, você usaria:

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

Para outros kits de ferramentas, você vai precisar para nos dar mais informações. - É sempre vai ser dependente do kit de ferramentas

Outras dicas

Ele não precisa sempre de ser dependente-toolkit ou a pessoa não precisa sempre usar os FontMetrics aproximar, uma vez que requer um para primeiro obter um objeto de gráficos que está ausente em um container web ou em um ambiente sem cabeça.

Eu testei isso em um servlet web e faz o cálculo da largura do 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());

Adicionar os valores necessários para estas dimensões para criar qualquer margem requerida.

Use o método getWidth na seguinte classe:

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

}

Eu, pessoalmente, estava à procura de algo para me deixar calcular a área seqüência de várias linhas, para que eu pudesse determinar se determinada área é grande o suficiente para imprimir a string -. Com a preservação fonte específica

Espero que seria seguro algum tempo para um outro cara que pode querer fazer trabalho semelhante em java então só queria compartilhar a solução:

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 em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top