Domanda

Come calcolare la lunghezza (in pixel) di una stringa in Java?

Preferibile senza usare Swing.

EDIT: Vorrei disegnare la stringa usando drawString () in Java2D e usa la lunghezza per il ritorno a capo automatico.

È stato utile?

Soluzione

Se vuoi semplicemente usare AWT, usa Graphics.getFontMetrics (facoltativamente specificando il carattere, per uno non predefinito) per ottenere un FontMetrics e quindi FontMetrics.stringWidth per trovare la larghezza della stringa specificata.

Ad esempio, se hai una variabile Graphics chiamata g , dovresti usare:

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

Per altri toolkit, dovrai fornirci ulteriori informazioni: dipenderà sempre dal toolkit.

Altri suggerimenti

Non deve sempre essere dipendente dal toolkit o non è sempre necessario utilizzare l'approccio FontMetrics poiché richiede prima di ottenere un oggetto grafico che è assente in un contenitore web o in un ambiente senza testa.

Ho provato questo in un servlet web e calcola la larghezza del testo.

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

Aggiungi i valori necessari a queste dimensioni per creare qualsiasi margine richiesto.

Utilizzare il metodo getWidth nella seguente 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();
  }

}

Personalmente stavo cercando qualcosa che mi permettesse di calcolare l'area della stringa multilinea, in modo da poter determinare se una determinata area è abbastanza grande per stampare la stringa, preservando il carattere specifico.

Spero che sia sicuro un po 'di tempo per un altro ragazzo che potrebbe voler fare un lavoro simile in Java, quindi volevo solo condividere la soluzione:

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;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top