2023-06-16 (金) 08:17:14
  • category: swing folder: CreateFont title: Fontをファイルから取得 tags: [Font, JTextArea] author: aterai pubdate: 2005-03-07T02:07:13+09:00 description: TrueTypeフォントをファイルから読み込み、ASCII artを表示します。 image: https://lh6.googleusercontent.com/_9Z4BYR88imo/TQTKOUJYB7I/AAAAAAAAAVo/K2rl3dXD4ic/s800/CreateFont.png

概要

TrueTypeフォントをファイルから読み込み、ASCII artを表示します。
http://terai.xrea.jp/swing/createfont/screenshot.png

サンプルコード

#spanend
#spanadd
Font makeFont(URL url) {
#spanend
  Font font = null;
  try (InputStream is = url.openStream()) {
    font = Font.createFont(Font.TRUETYPE_FONT, is).deriveFont(12f);
  } catch (IOException | FontFormatException ex) {
    ex.printStackTrace();
  }
  return font;
#spanadd
}
#spanend
#spanadd
// Font makeFont(URL url) {
#spanend
#spanadd
//   Font font = null;
#spanend
#spanadd
//   InputStream is = null;
#spanend
#spanadd
//   try {
#spanend
#spanadd
//     is = url.openStream();
#spanend
#spanadd
//     font = (Font.createFont(Font.TRUETYPE_FONT, is)).deriveFont(12f);
#spanend
#spanadd
//     is.close();
#spanend
#spanadd
//   } catch (IOException ioe) {
#spanend
#spanadd
//     ioe.printStackTrace();
#spanend
#spanadd
//   } catch (FontFormatException ffe) {
#spanend
#spanadd
//     ffe.printStackTrace();
#spanend
#spanadd
//   } finally {
#spanend
#spanadd
//     if (is != null) {
#spanend
#spanadd
//       try {
#spanend
#spanadd
//         is.close();
#spanend
#spanadd
//       } catch (IOException ioex) {
#spanend
#spanadd
//         ioex.printStackTrace();
#spanend
#spanadd
//       }
#spanend
#spanadd
//     }
#spanend
#spanadd
//   }
#spanend
#spanadd
//   return font;
#spanend
#spanadd
// }
#spanend
#spanadd
View in GitHub: Java, Kotlin
private static Font makeFont(String rpath) {
  Font font = null;
  InputStream is = null;
  try {
    is = MyCellRenderer.class.getResourceAsStream(rpath);
    font = (Font.createFont(Font.TRUETYPE_FONT, is)).deriveFont(12.0f);
    is.close();
  }catch(IOException ioe) {
    ioe.printStackTrace();
    throw new InternalError(ioe.getMessage());
  }catch(FontFormatException ffe) {
    ffe.printStackTrace();
    throw new InternalError(ffe.getMessage());
  }finally{
    if(is!=null) {
      try {
        is.close();
      }catch(IOException ioex) {
        ioex.printStackTrace();
        throw new InternalError(ioex.getMessage());
      }
    }
  }
  return font;
}

解説

上記のサンプルでは、Font.createFont(...)メソッドで.ttfファイルからフォントを作成しています。

参考リンク

コメント