libgdx中文输出、bitmapFont输出中文、bitmapFont输出文字、输出字体文字

libgdx中文输出、bitmapFont输出中文、bitmapFont输出文字、输出字体文字

libgdx中文输出、bitmapFont输出中文、bitmapFont输出文字、输出字体文字。jdk17+2023年11月1日14:08:44最新、

转自:https://lingkang.top/archives/libgdx-zhong-wen-shu-chu

Maven依赖

xml 复制代码
    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <gdx.version>1.12.0</gdx.version>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/com.badlogicgames.gdx/gdx -->
        <dependency>
            <groupId>com.badlogicgames.gdx</groupId>
            <artifactId>gdx</artifactId>
            <version>${gdx.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.badlogicgames.gdx/gdx-backend-lwjgl3 -->
        <dependency>
            <groupId>com.badlogicgames.gdx</groupId>
            <artifactId>gdx-backend-lwjgl3</artifactId>
            <version>${gdx.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.badlogicgames.gdx/gdx-platform -->
        <dependency>
            <groupId>com.badlogicgames.gdx</groupId>
            <artifactId>gdx-platform</artifactId>
            <version>${gdx.version}</version>
            <classifier>natives-desktop</classifier>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.badlogicgames.gdx/gdx-freetype -->
        <dependency>
            <groupId>com.badlogicgames.gdx</groupId>
            <artifactId>gdx-freetype</artifactId>
            <version>${gdx.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.badlogicgames.gdx/gdx-freetype-platform -->
        <dependency>
            <groupId>com.badlogicgames.gdx</groupId>
            <artifactId>gdx-freetype-platform</artifactId>
            <version>${gdx.version}</version>
            <classifier>natives-desktop</classifier>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>2.0.9</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>2.0.9</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.30</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>17</source>
                    <target>17</target>
                    <!-- 编译后保持方法形参名称不变 -->
                    <!--<compilerArgs>
                        <arg>-parameters</arg>
                    </compilerArgs>-->
                </configuration>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>tencent</id>
            <name>tencent</name>
            <layout>default</layout>
            <url>http://mirrors.cloud.tencent.com/nexus/repository/maven-public/</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <releases>
                <enabled>true</enabled>
            </releases>
        </repository>
        <repository>
            <id>nexus</id>
            <name>Nexus</name>
            <layout>default</layout>
            <url>https://s01.oss.sonatype.org/content/repositories/snapshots</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
            <releases>
                <enabled>true</enabled>
            </releases>
        </repository>
        <repository>
            <id>aliyunmaven</id>
            <url>https://maven.aliyun.com/repository/public</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

代码调用

java 复制代码
      protected BitmapFont bitmapFont;  
      //加载 仿宋字体
      FreeTypeFontGenerator generator = new FreeTypeFontGenerator(new FileHandle("C:\\Windows\\Fonts\\simfang.ttf"));
         
      bitmapFont = new SmartBitmapFont(generator,50);
 
       // 绘制
      bitmapFont.draw(batch, "欢迎", 0, 300);// 左下角起点,向上300个高度

通过重写 BitmapFont 进行读取字体输出

java 复制代码
package top.lingkang.yzcy.utils;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.g2d.freetype.FreeType;
import com.badlogic.gdx.graphics.g2d.freetype.FreeType.Face;
import com.badlogic.gdx.graphics.g2d.freetype.FreeType.SizeMetrics;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator.FreeTypeBitmapFontData;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator.FreeTypeFontParameter;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator.GlyphAndBitmap;
import com.badlogic.gdx.utils.GdxRuntimeException;

import java.lang.reflect.Field;

/**
 * 对BitmapFont进行改写,让文字获取直接从字体中获取
 * 调用方式:
 * <pre>
 *     protected BitmapFont bitmapFont; <br/>
 *     //加载 仿宋字体
 *     FreeTypeFontGenerator generator = new FreeTypeFontGenerator(new FileHandle("C:\\Windows\\Fonts\\simfang.ttf"));
 *     <br/> <br/>
 *     bitmapFont = new SmartBitmapFont(generator,50);
 *
 *     <br/>
 *     bitmapFont.draw(batch, "欢迎", 0, 300);// 左下角起点,向上300个高度
 * </pre>
 */
public class SmartBitmapFont extends BitmapFont {

    // 不应该在此对此进行 dispose ,让上层进行 dispose
    private FreeTypeFontGenerator generator;
    private FreeTypeBitmapFontData data;
    private FreeTypeFontParameter parameter;

    public SmartBitmapFont(FreeTypeFontGenerator generator, int fontSize) {
        if (generator == null)
            throw new GdxRuntimeException("lazyBitmapFont global generator must be not null to use this constructor.");
        this.generator = generator;
        FreeTypeFontParameter param = new FreeTypeFontParameter();
        param.size = fontSize;
        this.parameter = param;
        this.data = new LazyBitmapFontData(generator, fontSize, this);
        try {
            Field f = getClass().getSuperclass().getDeclaredField("data");
            f.setAccessible(true);
            f.set(this, data);
        } catch (Exception e) {
            e.printStackTrace();
        }

        genrateData();
    }

    private void genrateData() {
        Face face = null;
        try {
            Field field = generator.getClass().getDeclaredField("face");
            field.setAccessible(true);
            face = (Face) field.get(generator);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        // set general font data
        SizeMetrics fontMetrics = face.getSize().getMetrics();

        // Set space glyph.
        Glyph spaceGlyph = data.getGlyph(' ');
        if (spaceGlyph == null) {
            spaceGlyph = new Glyph();
            spaceGlyph.xadvance = (int) data.scaleX;//spaceWidth
            spaceGlyph.id = (int) ' ';
            data.setGlyph(' ', spaceGlyph);
        }
        if (spaceGlyph.width == 0)
            spaceGlyph.width = (int) (spaceGlyph.xadvance + data.padRight);

        // set general font data
        data.flipped = parameter.flip;
        data.ascent = FreeType.toInt(fontMetrics.getAscender());
        data.descent = FreeType.toInt(fontMetrics.getDescender());
        data.lineHeight = FreeType.toInt(fontMetrics.getHeight());

        // determine x-height
        for (char xChar : data.xChars) {
            if (!face.loadChar(xChar, FreeType.FT_LOAD_DEFAULT))
                continue;
            data.xHeight = FreeType.toInt(face.getGlyph().getMetrics().getHeight());
            break;
        }
        if (data.xHeight == 0)
            throw new GdxRuntimeException("No x-height character found in font");
        for (char capChar : data.capChars) {
            if (!face.loadChar(capChar, FreeType.FT_LOAD_DEFAULT))
                continue;
            data.capHeight = FreeType.toInt(face.getGlyph().getMetrics().getHeight());
            break;
        }

        // determine cap height
        if (data.capHeight == 1)
            throw new GdxRuntimeException("No cap character found in font");
        data.ascent = data.ascent - data.capHeight;
        data.down = -data.lineHeight;
        if (parameter.flip) {
            data.ascent = -data.ascent;
            data.down = -data.down;
        }

    }

    @Override
    public void dispose() {
        setOwnsTexture(true);
        super.dispose();
        data.dispose();
    }

    class LazyBitmapFontData extends FreeTypeBitmapFontData {

        private FreeTypeFontGenerator generator;
        private int fontSize;
        private SmartBitmapFont font;
        private int page = 1;

        public LazyBitmapFontData(FreeTypeFontGenerator generator, int fontSize, SmartBitmapFont lbf) {
            this.generator = generator;
            this.fontSize = fontSize;
            this.font = lbf;
        }

        public Glyph getGlyph(char ch) {
            Glyph glyph = super.getGlyph(ch);
            if (glyph == null)
                glyph = generateGlyph(ch);
            return glyph;
        }

        protected Glyph generateGlyph(char ch) {
            GlyphAndBitmap gab = generator.generateGlyphAndBitmap(ch, fontSize, false);
            if (gab == null || gab.bitmap == null)// 未找到文字字符: ch
                return null;

            Pixmap map = gab.bitmap.getPixmap(Format.RGBA8888, Color.WHITE, 9);
            TextureRegion rg = new TextureRegion(new Texture(map));
            map.dispose();

            font.getRegions().add(rg);

            gab.glyph.page = page++;
            super.setGlyph(ch, gab.glyph);
            setGlyphRegion(gab.glyph, rg);
            return gab.glyph;
        }
    }
}

效果

相关推荐
资源分享助手13 小时前
我!勇者?The Warrior免安装中文版下载与玩法体验
游戏
云起SAAS15 小时前
抖音小游戏源码 - 消消乐 | 含激励广告+成就系统 | 开箱即用商业级消除游戏模板
android·游戏·广告联盟·看激励广告联盟流量主·抖音小游戏源码 - 消消乐
津津有味道16 小时前
一键写入启动游戏NDEF复合记录NFC标签vb6源码
游戏·标签·nfc·ndef·复合记录
游乐码16 小时前
Unity基础(四)向量相关
游戏·unity·游戏引擎
阿阳微客19 小时前
网易Buff游戏搬砖,长期可做!
笔记·学习·游戏
Kurisu57519 小时前
探灵直播2026最新官方正版免费下载 一键转存 永久更新 (看到速转存 资源随时走丢)
游戏·游戏引擎·游戏程序·动画·关卡设计
STDD20 小时前
Abiotic Factor多人生存建筑游戏《非生物因素》 专用服务器搭建教程
服务器·数据库·游戏
开开心心就好21 小时前
带OCR识别的电子发票打印工具
运维·javascript·科技·游戏·青少年编程·ocr·powerpoint
经济元宇宙1 天前
HOPE星火燎原不是希望工程,也不是游戏项目:项目名称与定位澄清
游戏
2601_950316061 天前
XBOX360 KINECT体感游戏合集109个
游戏