Java Font Text Size getStringDimensions(Graphics2D graphics, Font font, String[] stringsByLine)

Here you can find the source of getStringDimensions(Graphics2D graphics, Font font, String[] stringsByLine)

Description

get String Dimensions

License

Apache License

Declaration

public static Dimension getStringDimensions(Graphics2D graphics, Font font, String[] stringsByLine) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;

import java.awt.Graphics2D;

import java.awt.font.TextLayout;

import java.awt.geom.Rectangle2D;

import java.text.AttributedString;

public class Main {
    private final static String NEWLINE_SEPARATOR = System.getProperty("line.separator");

    public static Dimension getStringDimensions(Graphics2D graphics, Font font, String[] stringsByLine) {
        FontMetrics fontMetrics = graphics.getFontMetrics(font);
        int overallWidth = 0;
        int overallHeight = 0;
        for (String string : stringsByLine) {
            int width = fontMetrics.stringWidth(string);
            int height = fontMetrics.getHeight();
            overallWidth = Math.max(overallWidth, width);
            overallHeight += height;/*ww  w.j a va  2s .  c om*/
        }
        return new Dimension(overallWidth, overallHeight);
    }

    public static Dimension getStringDimensions(Graphics2D graphics, Font font, String string) {
        FontMetrics fontMetrics = graphics.getFontMetrics(font);
        String[] lines = string.split(NEWLINE_SEPARATOR);

        // count the number of newlines in text
        int numberOfLines = lines.length;
        int heightOfOneLine = fontMetrics.getHeight();
        int totalHeight = numberOfLines * heightOfOneLine;

        int maxWidth = 0;
        for (String line : lines) {
            maxWidth = Math.max(fontMetrics.stringWidth(line), maxWidth);
        }

        return new Dimension(maxWidth, totalHeight);

    }

    public static Dimension getStringDimensions(Graphics2D graphics, AttributedString attributedString) {
        TextLayout textLayout = new TextLayout(attributedString.getIterator(), graphics.getFontRenderContext());
        Rectangle2D bounds = textLayout.getBounds();
        return new Dimension((int) bounds.getWidth(), (int) bounds.getHeight());
    }
}

Related

  1. getSize(Font font)
  2. getStringDimension(Component comp, String str)
  3. getStringDisplaySize(String input)
  4. getStringSize(final Graphics g, final Font font, final String text)
  5. getStringSize(Graphics g, String text, Font font)
  6. getStringSize(String textToMeasure, Font displayFont)