我下載了字體“Retro Gaming”(https://www.dafont.com/retro-gaming.font)以在我的 Java 專案中使用它。這個專案需要在我運行它的每臺機器上運行。我的問題是:如何或在哪里放置字體以便所有計算機(即使沒有安裝)都可以使用它?我認為 gradle 可能是一個不錯的解決方案,但我在互聯網上一無所獲。
代碼示例如下:
public PlayerOneLabel() {
this.setText("PLAYER 1");
this.setForeground(Color.white);
this.setFont(new Font("Retro Gaming", Font.BOLD, CenterOnDefaultScreen.center().height*2/100));
}
這顯然只能在已安裝字體的 PC 上運行。
uj5u.com熱心網友回復:
將字體檔案保存在您喜歡的任何位置...將其與其余游戲檔案一起放置或放置在資源檔案夾中。如果它只是為了你的游戲,它不需要去特別的地方。您可以在需要時使用以下方法加載字體:
/**
* Loads a Font file and returns it as a Font Object. This method does try to
* utilize the proper Font Type Resource (TrueType or Type1) but will default
* to TrueType if the resource type can not be established.
*
* @param fontFilePath (String) Full path and file name of the font to load.<br>
*
* @param fontStyle (Integer) The Font Style to use for the loaded font, for
* example:<pre>
*
* Font.PLAIN
* Font.BOLD
* Font.ITALIC
* Font.BOLDITALIC</pre>
*
* @param fontSize (Integer) The desired size of font.<br>
*
* @return (Font) A Font Object
*/
public Font loadFont(String fontFilePath, int fontStyle, int fontSize) {
Font font = null;
int fontTypeResource = Font.TRUETYPE_FONT;
if ((fontFilePath == null || fontFilePath.isEmpty()) || fontSize < 1) {
throw new IllegalArgumentException("loadFont() Method Error! Arguments "
"passed to this method must contain a file path OR a numerical "
"value other than 0!" System.lineSeparator());
}
String fileExt = (fontFilePath.contains(".") ? fontFilePath.substring(fontFilePath.lastIndexOf(".") 1) : "");
if (fontFilePath.isEmpty()) {
throw new IllegalArgumentException("loadFont() Method Error! An illegal "
"font file has been passed to this method (no file name "
"extension)!" System.lineSeparator());
}
switch (fileExt.toLowerCase()) {
case "fot":
case "t2":
case "otf":
case "ttf":
fontTypeResource = Font.TRUETYPE_FONT;
break;
// PostScript/Adobe
case "lwfn":
case "pfa":
case "pfb":
case "pdm":
fontTypeResource = Font.TYPE1_FONT;
break;
default:
fontTypeResource = Font.TRUETYPE_FONT;
}
try {
font = Font.createFont(fontTypeResource, new FileInputStream(
new File(fontFilePath))).deriveFont(fontStyle, fontSize);
}
catch (FileNotFoundException ex) {
Logger.getLogger("loadFont()").log(Level.SEVERE, null, ex);
}
catch (FontFormatException | IOException ex) {
Logger.getLogger("loadFont()").log(Level.SEVERE, null, ex);
}
return font;
}
以及如何使用它:
JLabel jLabel_1 = new JLabel("This is my Label Caption");
/* Assumes the .ttf file in within the application's project
directory. Use a getResource() mechanism when loading from
a resource directory. */
Font gameFont = loadFont("Retro Gaming.ttf", Font.BOLD, 18);
jLabel_1.setFont(gameFont);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/439430.html
上一篇:對齊磁區左下角
