Getting string size in java (without having a Graphics object available)

前端 未结 6 628
南方客
南方客 2021-01-11 12:37

I\'m trying to write application which need to draw many strings using Graphics2D class in Java. I need to get sizes of each String object (to calculate exact p

6条回答
  •  南笙
    南笙 (楼主)
    2021-01-11 13:30

    Besides using FontMetrics, a JLabel can be used to determine the size of both unformatted and (basic HTML) rendered text. Here is an example.

    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.GradientPaint;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    
    import java.awt.image.BufferedImage;
    
    import javax.swing.JOptionPane;
    import javax.swing.JLabel;
    import javax.swing.ImageIcon;
    
    /** Sample code obtained from a thread on the Oracle forums that I cannot
    locate at this instant.  My question was related to an unexpected rendering of
    JLabel.  It was resolved by the 'added this' line courtesy of Darryl Burke. */
    public class LabelRenderTest {
    
      String title = ""
              + "

    Do U C Me?

    " + "Here is a long string that will wrap. " + "The effect we want is a multi-line label."; LabelRenderTest() { BufferedImage image = new BufferedImage( 640, 480, BufferedImage.TYPE_INT_RGB); Graphics2D imageGraphics = image.createGraphics(); GradientPaint gp = new GradientPaint( 20f, 20f, Color.blue, 620f, 460f, Color.white); imageGraphics.setPaint(gp); imageGraphics.fillRect(0, 0, 800, 600); JLabel textLabel = new JLabel(title); textLabel.setSize(textLabel.getPreferredSize()); // <==== added this Dimension d = textLabel.getPreferredSize(); BufferedImage bi = new BufferedImage( d.width, d.height, BufferedImage.TYPE_INT_ARGB); Graphics g = bi.createGraphics(); g.setColor(new Color(255, 255, 255, 128)); g.fillRoundRect( 0, 0, bi.getWidth(null), bi.getHeight(null), 15, 10); g.setColor(Color.black); textLabel.paint(g); Graphics g2 = image.getGraphics(); g2.drawImage(bi, 20, 20, null); ImageIcon ii = new ImageIcon(image); JLabel imageLabel = new JLabel(ii); JOptionPane.showMessageDialog(null, imageLabel); } public static void main(String[] args) { LabelRenderTest ist = new LabelRenderTest(); } }

    Edit 1: As to your "many strings" comment. Paint the strings to a BufferedImage that is only regenerated if needed. Use the buffered image each time paintComponent() is called.

提交回复
热议问题