आप FontMetrics कक्षा के getWidths() विधि का उपयोग कर सकते हैं। जावाडॉक के अनुसार:
फ़ॉन्ट में पहले 256 वर्णों की अग्रिम चौड़ाई प्राप्त करता है। अग्रिम बाईं ओर बिंदु से चरित्र की आधार रेखा पर दाएं बिंदु तक दूरी है। ध्यान दें कि एक स्ट्रिंग का अग्रिम जरूरी नहीं है कि वह अपने पात्रों की प्रगति का योग हो।
आप 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();
स्रोत
2009-05-28 17:45:02
आप उदाहरण कोड जोड़ सकते हैं एक BufferedImage बनाने की आवश्यकता नहीं है कि? व्यावहारिक और सरल दृष्टिकोण के लिए – Jonik
+1; मैं आई और एम का उपयोग करता हूं। –