1. 程式人生 > >LibGDX_6.2: 常用系統控制元件: 標籤(Label)

LibGDX_6.2: 常用系統控制元件: 標籤(Label)

1. 標籤(Label)

標籤控制元件主要用於輸出文字資訊,在舞臺中展示一下文字內容,例如玩家分數,主角血值,關卡說明等。

由於標籤是用來展示文字的,所以使用標籤首先要有點陣圖字型(BitmapFont)來 提供字元顯示 ,這裡使用前面章節建立好的點陣圖檔案(bitmapfont.pngbitmapfont.fnt),把這兩個檔案複製到 assets 資原始檔夾中,這裡我在 assets 中單獨建立一個資料夾 font 來存放這兩個字型檔案,如下圖所示:

sy_project.png

2. 程式碼示例: Label 的使用

package com.libgdx.test;

import com.badlogic.gdx.ApplicationAdapter;
import
com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.utils.viewport.StretchViewport; /** * 遊戲主程式的啟動入口類 */
public class MainGame extends ApplicationAdapter { // 視口世界的寬高統使用 480 * 800, 並統一使用伸展視口(StretchViewport) public static final float WORLD_WIDTH = 480; public static final float WORLD_HEIGHT = 800; // 舞臺 private Stage stage; // 標籤控制元件 private Label label; // 點陣圖字型 private BitmapFont bitmapFont; @Override
public void create() { // 使用伸展視口(StretchViewport)建立舞臺 stage = new Stage(new StretchViewport(WORLD_WIDTH, WORLD_HEIGHT)); /* * 第 1 步: 建立 BitmapFont */ // 讀取 bitmapfont.fnt 檔案建立點陣圖字型 bitmapFont = new BitmapFont(Gdx.files.internal("font/bitmapfont.fnt")); /* * 第 2 步: 建立 LabelStyle */ // 要建立 Label 首先要建立一個 Label 的樣式, 用於指明 Label 所使用的點陣圖字型, 背景圖片, 顏色等 Label.LabelStyle style = new Label.LabelStyle(); // 指定 Label 的背景, 可用紋理區域 textureRegion(在這裡背景我就不再設定) // style.background = new TextureRegionDrawable(textureRegion); // 指定 Label 所使用的點陣圖字型 style.font = bitmapFont; // 指定 Label 字型的 RGBA 顏色, 在這裡我設定為紅色 style.fontColor = new Color(1, 0, 0, 1); /* * 第 3 步: 建立 Label */ // 根據 Label 的樣式建立 Label, 第一個引數表示顯示的文字(要顯示的文字字元必須在 BitmapFont 中存在) label = new Label("Hello Label", style); // 也可以通過方法設定或獲取文字 // label.setText("Hello"); // String text = label.getText().toString(); // 設定 Label 的顯示位置 label.setPosition(50, 400); // 可以通過設定字型的縮放比來控制字型顯示的大小 label.setFontScale(1.5f); /* * 第 4 步: 新增到舞臺 */ // 新增 label 到舞臺 stage.addActor(label); } @Override public void render() { // 黑色清屏 Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // 更新舞臺邏輯 stage.act(); // 繪製舞臺 stage.draw(); } @Override public void dispose() { // 應用退出時釋放資源 if (bitmapFont != null) { bitmapFont.dispose(); } if (stage != null) { stage.dispose(); } } }

執行結果:

sy_result.png