【问题标题】:How to load and use ttf font from jar [duplicate]如何从jar中加载和使用ttf字体[重复]
【发布时间】:2015-07-12 20:51:08
【问题描述】:

尝试写一个类:

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);
  }

显示消息,但未使用指定的字体。

【问题讨论】:

  • 顺便说一句,您忘记close() 输入流。使用try-finallytry-with-resources。哦,fnt_stream 不符合正确的 Java 风格(只允许 MULTI_WORD_CONSTANTS 包含下划线)。

标签: java fonts graphics2d truetype


【解决方案1】:

您必须在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
}

看看here

【讨论】:

    【解决方案2】:

    在其他cmets旁边

    替换

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

    通过

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

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

    有关字体的更多信息,请查看有关 Physical and Logical Fonts 的 Oracle 教程

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-21
      • 2011-02-11
      • 1970-01-01
      • 2012-05-29
      • 1970-01-01
      • 2015-02-07
      • 1970-01-01
      • 2017-07-20
      相关资源
      最近更新 更多