我正在列出用户机器上可用的所有等宽字体.我可以通过以下方式获取Swing中的所有字体:
String[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment() .getAvailableFontFamilyNames();@H_404_4@有没有办法弄清楚哪些是均匀的? @H_404_4@提前致谢.
解决方法
您可以使用
FontMetrics课程的
getWidths()方法.根据JavaDoc:
@H_404_4@Gets the advance widths of the first 256 characters in the Font. The advance is the distance from the leftmost point to the rightmost point on the character’s baseline. Note that the advance of a String is not necessarily the sum of the advances of its characters.@H_404_4@您可以使用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();