如何从jar加载和使用ttf字体[复制]

时间:2023-02-09 15:47:12

This question already has an answer here:

这个问题在这里已有答案:

Trying to write a class:

试着写一堂课:

private void gameLevel(Graphics g) {
  try {
     InputStream fnt_stream = getClass().getResourceAsStream("resources/iomanoid.ttf");
     Font myFont = Font.createFont(Font.TRUETYPE_FONT, fnt_stream);
     Font Iomanoid = new Font("Iomanoid", Font.BOLD, 40);

     String msg = "Level";
     g.setColor(Color.black);
     g.setFont(Iomanoid);
     g.drawString(msg, 111,111);
  } catch (Exception ex) {
     System.out.println(ex);
  }

The message appears, but not with the font specified.

将显示该消息,但不会显示指定的字体。

2 个解决方案

#1


Beside other comments

除了其他评论

replace

Font Iomanoid = new Font("Iomanoid", Font.BOLD, 40);

by

Font iomanoid = myFont.deriveFont(Font.BOLD, 40f);

this font needs afterwards to be registered (as mentioned by mushfek0001)

之后需要注册此字体(如mushfek0001所述)

For more information about fonts have a look at the Oracle tutorial about Physical and Logical Fonts

有关字体的更多信息,请查看有关物理和逻辑字体的Oracle教程

#2


You will have to register the newly created font in GraphicsEnvironment. Like this

您必须在GraphicsEnvironment中注册新创建的字体。像这样

try {
     GraphicsEnvironment ge =  GraphicsEnvironment.getLocalGraphicsEnvironment();
     ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("path/to/your/font/sampleFont.ttf"));
} catch (IOException|FontFormatException e) {
     //Handle exception
}

Take a look at here.

看看这里。

#1


Beside other comments

除了其他评论

replace

Font Iomanoid = new Font("Iomanoid", Font.BOLD, 40);

by

Font iomanoid = myFont.deriveFont(Font.BOLD, 40f);

this font needs afterwards to be registered (as mentioned by mushfek0001)

之后需要注册此字体(如mushfek0001所述)

For more information about fonts have a look at the Oracle tutorial about Physical and Logical Fonts

有关字体的更多信息,请查看有关物理和逻辑字体的Oracle教程

#2


You will have to register the newly created font in GraphicsEnvironment. Like this

您必须在GraphicsEnvironment中注册新创建的字体。像这样

try {
     GraphicsEnvironment ge =  GraphicsEnvironment.getLocalGraphicsEnvironment();
     ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("path/to/your/font/sampleFont.ttf"));
} catch (IOException|FontFormatException e) {
     //Handle exception
}

Take a look at here.

看看这里。