Question

Comment calculer la longueur (en pixels) d'une chaîne en Java?

Préférable sans utiliser Swing.

EDIT: Je voudrais dessiner la chaîne en utilisant drawString () dans Java2D et utilisez la longueur pour le retour à la ligne.

Était-ce utile?

La solution

Si vous souhaitez simplement utiliser AWT, utilisez Graphics.getFontMetrics (spécifiant éventuellement la police, pour une police autre que celle par défaut) pour obtenir un FontMetrics , puis FontMetrics.stringWidth pour trouver la largeur de la chaîne spécifiée.

Par exemple, si vous avez une variable Graphics appelée g , vous utiliserez:

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

Pour les autres kits d’outils, vous devrez nous donner plus d’informations - cela dépendra toujours de celui-ci.

Autres conseils

Cela n’a pas toujours besoin d’être dépendant de la boîte à outils ou d’utiliser l’approche FontMetrics, car il est nécessaire d’obtenir d’abord un objet graphique absent dans un conteneur Web ou dans un environnement sans tête.

J'ai testé cela dans une servlet Web et il calcule la largeur du texte.

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

Ajoutez les valeurs nécessaires à ces dimensions pour créer toute marge requise.

Utilisez la méthode getWidth dans la classe suivante:

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

}

Personnellement, je recherchais quelque chose qui me permette de calculer la zone de chaîne multiligne afin de pouvoir déterminer si une zone donnée est suffisamment grande pour imprimer la chaîne, tout en préservant une police spécifique.

J'espère que cela évitera un peu de temps à un autre gars qui voudra peut-être faire le même travail en Java alors je voulais juste partager la solution:

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;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top