Question

Is there a (neat) way, instead of getting the height of a particular font size, getting a font size of a particular font (SansSerif in this case) that produces a given height?

I could of course loop through font sizes or use some form of binary chop, but if possible I would like to use something a bit cleaner and less resource intensive. The best way I've found is using something like this.

Was it helpful?

Solution

When searching, TextLayout, shown here and here, will provide the tightest bounds for a given text.

OTHER TIPS

There's no easy way.

First, you know that java provides just five logical font families. All other fonts aren't garanteed to be present in the system that you'll run the program.

Then, no, there's no automatically mapping of the fonts' properties on your system. You'll have to load them all and loop searching the measure that you want.

with this code you can loop the available fonts:

import java.awt.Font;
import java.awt.GraphicsEnvironment;
public class MainClass {
  public static void main(String[] a) {
    GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
    Font[] fonts = e.getAllFonts(); // Get the fonts
    for (Font f : fonts) {
      System.out.println(f.getFontName());
    }
  }
}

and then choose the one that suits your needs. Change the code to display the information you want: weight, for example.

Edit: Notice the They are merely font-type names recognized by the Java runtime which must be mapped to some physical font that is installed on your system observation in http://download.oracle.com/javase/1.3/docs/guide/intl/addingfonts.html.

Even the logical fonts aren't garanteed to be always the same. What you could do is the get the size of 10pt and calculate the font size. Like

font_size_in_points = ((10 * desidered_measure) / equivalent_measure_of_the_10pt)

FontMetrics metric = new FontMetrics(new Font("font"), Font.BOLD, 12);
metrics.getHeight()

Might be what you are looking for.

More info: http://download.oracle.com/javase/6/docs/api/java/awt/FontMetrics.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top