2009-10-06 14 views
11

Estoy usando java para dibujar texto, pero es difícil para mí calcular el ancho de la cadena. por ejemplo: zheng 中国 ... ¿Cuánto tiempo ocupará esta cadena?¿Cómo calcular el ancho de la fuente?

+0

duplicado posible de [ Calcule el ancho de visualización de una cadena en Java] (http://stackoverflow.com/questions/258486/calculate-the-display-width-of-a-string-in-java) – Zich

Respuesta

33

Para una sola cadena, puede obtener las métricas para la fuente de dibujo dada, y usar eso para calcular el tamaño de la cadena. Por ejemplo:

String  message = new String("Hello, StackOverflow!"); 
Font  defaultFont = new Font("Helvetica", Font.PLAIN, 12); 
FontMetrics fontMetrics = new FontMetrics(defaultFont); 
//... 
int width = fontMetrics.stringWidth(message); 

Si usted tiene requisitos de diseño de texto más complejas, tales como el flujo de un párrafo de texto dentro de un ancho dado, puede crear un objeto java.awt.font.TextLayout, como este ejemplo (de los documentos):

Graphics2D g = ...; 
Point2D loc = ...; 
Font font = Font.getFont("Helvetica-bold-italic"); 
FontRenderContext frc = g.getFontRenderContext(); 
TextLayout layout = new TextLayout("This is a string", font, frc); 
layout.draw(g, (float)loc.getX(), (float)loc.getY()); 

Rectangle2D bounds = layout.getBounds(); 
bounds.setRect(bounds.getX()+loc.getX(), 
       bounds.getY()+loc.getY(), 
       bounds.getWidth(), 
       bounds.getHeight()); 
g.draw(bounds); 
+17

No se puede instalar tia el tipo FontMetrics. –

+3

Uso: FontMetrics fontMetrics = g.getFontMetrics(); –

+0

java.awt.FontMetrics es abstracto; no se puede crear una instancia FontMetrics metrics = new FontMetrics (font); Encontré en otro lado que tienes que poner un par de llaves vacías después de la (fuente) y antes del punto y coma. No tengo ni idea de porqué. FontMetrics metrics = new FontMetrics (font) {}; –

3

aquí es una aplicación sencilla que puede mostrar cómo utilizar FontMetrics al probar el ancho de una cadena:

import java.awt.*; 
import java.awt.event.*; 

import javax.swing.*; 

public class GUITest { 
    JFrame frame; 
    public static void main(String[] args){ 
     new GUITest(); 
    } 
    public GUITest() { 
     frame = new JFrame("test"); 
     frame.setSize(300,300); 
     addStuffToFrame(); 
     SwingUtilities.invokeLater(new Runnable(){ 
      public void run() { 
       frame.setVisible(true); 
      } 
     }); 
    }   

    private void addStuffToFrame() {  
     JPanel panel = new JPanel(new GridLayout(3,1)); 
     final JLabel label = new JLabel(); 
     final JTextField tf = new JTextField(); 
     JButton b = new JButton("calc sting width"); 
     b.addActionListener(new ActionListener(){ 
      public void actionPerformed(ActionEvent e) { 
       FontMetrics fm = label.getFontMetrics(label.getFont()); 
       String text = tf.getText(); 
       int textWidth = fm.stringWidth(text); 
       label.setText("text width for \""+text+"\": " +textWidth); 
      } 
     }); 
     panel.add(label); 
     panel.add(tf); 
     panel.add(b); 
     frame.setContentPane(panel); 
    } 


} 
0

Utilice el método getWidth en la clase siguiente:

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

} 
0

Usted puede encontrar desde Font.getStringBounds():

String string = "Hello World"; 
// Passing or initializing an instance of Font. 
Font font = ...; 
int width = (int) font.getStringBounds(string, new FontRenderContext(font.getTransform(), false, false)).getBounds().getWidth(); 
+2

Por favor explique su solución – Jens

Cuestiones relacionadas