---
category: swing
folder: FontCanDisplay
title: FontがUnicodeコードポイントで指定した文字のグリフを持って表示可能か確認する
tags: [Font]
author: aterai
pubdate: 2021-04-26T19:47:27+09:00
description: FontにUnicodeコードポイントで指定した文字のグリフが存在し、かつ表示可能か確認します。
image: https://drive.google.com/uc?id=1BR9NZACpykg8UXFiiAI7pFRE9UitBIbc
---
* Summary [#summary]
`Font`に`Unicode`コードポイントで指定した文字のグリフが存在し、かつ表示可能か確認します。
#download(https://drive.google.com/uc?id=1BR9NZACpykg8UXFiiAI7pFRE9UitBIbc)
* Source Code Examples [#sourcecode]
#code(link){{
int code = 0x1F512;
JLabel label = new JLabel(new String(Character.toChars(code)));
label.setFont(label.getFont().deriveFont(24f));
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setVerticalAlignment(SwingConstants.CENTER);
String[] columnNames = {"family", "name", "postscript name", "canDisplay", "isEmpty"};
DefaultTableModel model = new DefaultTableModel(null, columnNames) {
@Override public boolean isCellEditable(int row, int column) {
return false;
}
@Override public Class<?> getColumnClass(int column) {
return column > 2 ? Boolean.class : String.class;
}
};
JTable table = new JTable(model);
Font[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
Stream.of(fonts)
.map(f -> {
String txt = new String(Character.toChars(code));
FontRenderContext frc = getFontMetrics(f).getFontRenderContext();
return new Object[] {
f.getFamily(),
f.getName(),
f.getPSName(),
f.canDisplay(code),
f.createGlyphVector(frc, txt).getVisualBounds().isEmpty()
};
})
.forEach(model::addRow);
}}
* Description [#explanation]
* Description [#description]
上記のサンプルでは絵文字ロック🔒`U+1F512`がフォント一覧から選択したフォントで表示可能かをテストしています。
- `4`列目: `Font.canDisplay(int codePoint)`
-- この`Font`に指定された文字のグリフが含まれているかどうかを調べる
-- `false`の場合フォントが指定するゲタ文字が表示される
- `5`列目: `GlyphVector#getVisualBounds()#isEmpty()`
-- グリフのサイズが`0`かを調べる
-- 日本語環境の`Ubuntu 29.04`でフォントを`Serif`に指定すると`Font.canDisplay(int codePoint)`は`true`になるが、`GlyphVector#getVisualBounds()`はサイズ`0`で絵文字が表示されない場合がある?
* Reference [#reference]
- [https://docs.oracle.com/javase/jp/8/docs/api/java/awt/Font.html#canDisplay-int- Font (Java Platform SE 8)]
- [https://bugs.openjdk.org/browse/JDK-8269806 [JDK-8269806] Emoji rendering on Linux - Java Bug System]
* Comment [#comment]
#comment
#comment