0

在使用 java.awt.Graphics2D 绘制文本之前,我应该加载位图字体

@Override
protected void paintComponent(java.awt.Graphics graphics) {
    super.paintComponent(graphics);
    graphics.setFont(awtFont); // font should be loaded before it can be used
    graphics.drawString("text", 0, 0);
}

以下代码加载位图字体“BitmapFont.fnt”

package com.test;

import java.awt.*;
import java.io.IOException;
import java.io.InputStream;

public class Runner {

    public static void main(String[] args){
        Font awtFont;  
        InputStream fontResource = Runner.class.getResourceAsStream("BitmapFont.fnt");
        try {
            awtFont = Font.createFont(Font.TRUETYPE_FONT, fontResource);
        } catch (Exception e) {
            e.printStackTrace();
            try{
                awtFont = Font.createFont(Font.TYPE1_FONT, fontResource);
            }catch (Exception e1){
                e1.printStackTrace();
            }
        }
    }

}

抛出异常

java.awt.FontFormatException: Unsupported sfnt C:\Users\Dmitry\AppData\Local\Temp\+~JF454779897929138835.tmp
at sun.font.TrueTypeFont.init(TrueTypeFont.java:488)
at sun.font.TrueTypeFont.<init>(TrueTypeFont.java:162)
at sun.font.FontManager.createFont2D(FontManager.java:2474)
at java.awt.Font.<init>(Font.java:570)
at java.awt.Font.createFont(Font.java:896)
at com.test.Runner.main(Runner.java:12)

 java.awt.FontFormatException: bad pfa font
at sun.font.Type1Font.verifyPFA(Type1Font.java:298)
at sun.font.Type1Font.verify(Type1Font.java:276)
at sun.font.Type1Font.<init>(Type1Font.java:148)
at sun.font.FontManager.createFont2D(FontManager.java:2477)
at java.awt.Font.<init>(Font.java:570)
at java.awt.Font.createFont(Font.java:896)
at com.test.Runner.main(Runner.java:12)

分别。如何加载 BitmapFont.fnt 并使用 java.awt.Graphics2D 进行渲染?

4

0 回答 0