测试Font是否在Java中是等宽的

时间:2009-05-28 17:04:23

标签: java swing fonts

我正在尝试列出用户计算机上可用的所有等宽字体。我可以通过Swing获得所有字体系列:

String[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment()
                                    .getAvailableFontFamilyNames();

有没有办法弄清楚哪些是等宽的?

提前致谢。

5 个答案:

答案 0 :(得分:6)

一个更简单的方法,不需要让BufferedImage来获取Graphics对象等。

    Font fonts[] = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
    List<Font> monoFonts1 = new ArrayList<>();

    FontRenderContext frc = new FontRenderContext(null, RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT, RenderingHints.VALUE_FRACTIONALMETRICS_DEFAULT);
    for (Font font : fonts) {
        Rectangle2D iBounds = font.getStringBounds("i", frc);
        Rectangle2D mBounds = font.getStringBounds("m", frc);
        if (iBounds.getWidth() == mBounds.getWidth()) {
            monoFonts1.add(font);
        }
    }

答案 1 :(得分:4)

您可以使用getWidths()类的FontMetrics方法。根据JavaDoc:

  

获取Font中前256个字符的advance width。前进是角色基线上从最左侧点到最右侧点的距离。请注意,String的前进不一定是其字符的前进之和。

您可以使用FontMetrics类的charWidth(char)方法。例如:

Set<String> monospaceFontFamilyNames = new HashSet<String>();

GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontFamilyNames = graphicsEnvironment.getAvailableFontFamilyNames();

BufferedImage bufferedImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics graphics = bufferedImage.createGraphics();

for (String fontFamilyName : fontFamilyNames) {
    boolean isMonospaced = true;

    int fontStyle = Font.PLAIN;
    int fontSize = 12;
    Font font = new Font(fontFamilyName, fontStyle, fontSize);
    FontMetrics fontMetrics = graphics.getFontMetrics(font);

    int firstCharacterWidth = 0;
    boolean hasFirstCharacterWidth = false;
    for (int codePoint = 0; codePoint < 128; codePoint++) { 
        if (Character.isValidCodePoint(codePoint) && (Character.isLetter(codePoint) || Character.isDigit(codePoint))) {
            char character = (char) codePoint;
            int characterWidth = fontMetrics.charWidth(character);
            if (hasFirstCharacterWidth) {
                if (characterWidth != firstCharacterWidth) {
                    isMonospaced = false;
                    break;
                }
            } else {
                firstCharacterWidth = characterWidth;
                hasFirstCharacterWidth = true;
            }
        }
    }

    if (isMonospaced) {
        monospaceFontFamilyNames.add(fontFamilyName);
    }
}

graphics.dispose();

答案 2 :(得分:3)

比较几个字符的绘制长度(m,i,1,...应该是一个好的集合)。

对于等宽字体,它们都是相同的,对于可变宽度字体,它们不会。

答案 3 :(得分:1)

根据this response,Java对底层字体细节知之甚少,因此您必须对字体的尺寸进行一些比较。

答案 4 :(得分:1)

可能不适用于您的情况,但如果您只想将字体设置为等宽字体,请使用逻辑字体名称:

Font mono = new Font("Monospaced", Font.PLAIN, 12);

这将是您系统上保证的等宽字体。