Integrating compiled libSDL3_ttf.so on Android Интеграция собранной библиотеки libSDL3_ttf.so на Android

A step-by-step guide to adding SDL3_ttf support to your Android project, handling font assets, and rendering TrueType text on mobile devices. Пошаговое руководство по добавлению поддержки SDL3_ttf в ваш Android-проект, работе с файлами шрифтов и отрисовке текста TrueType на мобильных устройствах.

Before starting this guide, make sure you have completed the foundational tutorials: Перед началом работы убедитесь, что вы выполнили предыдущие руководства:

Step 1: Download Base Template and Rename Project Шаг 1: Скачивание базового шаблона и переименование проекта

First, download the base starter project template depending on your language preference: Сначала скачайте базовый шаблон проекта в зависимости от используемого языка:

Rename your project folder to integrate-sdl3-ttf-android-c (or integrate-sdl3-ttf-android-cpp). Переименуйте папку проекта в integrate-sdl3-ttf-android-c (или integrate-sdl3-ttf-android-cpp).

Step 2: Update CMakeLists.txt Шаг 2: Обновление CMakeLists.txt

Open CMakeLists.txt in the root directory and update it to link both SDL3 and SDL3_ttf libraries: Откройте CMakeLists.txt в корне проекта и обновите его для связывания обоих библиотек (SDL3 и SDL3_ttf):

Step 3: Configure Gradle Source Sets Шаг 3: Настройка Source Sets в Gradle

Open android-project/app/build.gradle and set the sourceSets block inside android { ... }. This instructs Gradle to bundle assets directly from the project's root assets folder: Откройте android-project/app/build.gradle и настройте блок sourceSets внутри android { ... }. Это укажет Gradle упаковывать ассеты напрямую из корневой папки assets:

android {
    namespace "com.example.myapp"
    compileSdkVersion 35

    defaultConfig {
        // ...
    }

    // Direct Gradle to fetch assets straight from the root project folder
    sourceSets {
        main {
            assets.srcDirs = ['../../assets']
        }
    }

    externalNativeBuild {
        cmake {
            path '../../CMakeLists.txt'
        }
    }
}

Step 4: Setup Project Assets Шаг 4: Настройка ресурсов (Assets)

1. Download LiberationSans-Regular.ttf from the official Liberation Fonts Releases. 1. Скачайте файл LiberationSans-Regular.ttf из официальных релизов Liberation Fonts Releases.

2. Create a new directory path in the root folder: assets/fonts. 2. Создайте новую папку в корне вашего проекта: assets/fonts.

3. Place the downloaded font file into assets/fonts and name it LiberationSans-Regular.ttf. 3. Поместите скачанный файл шрифта в assets/fonts и назовите его LiberationSans-Regular.ttf.

Step 5: Write the C Source Code Шаг 5: Написание исходного кода на C

Replace the contents of src/main.c with the following code to initialize TTF, load a font, and render text using SDL3_ttf: Замените содержимое файла src/main.c следующим кодом для инициализации TTF, загрузки шрифта и отрисовки текста с помощью SDL3_ttf:

Step 6: Build and Run on Android Шаг 6: Сборка и запуск на Android

Run the provided helper scripts in your command prompt to compile the app and push it directly to your connected device: Запустите готовые батч-скрипты в командной строке для сборки и автоматической установки на подключенное устройство:

build-apk
install-apk

Once installed, tap the application icon on your smartphone to launch it and view the rendered text. После завершения установки нажмите на иконку приложения на смартфоне, чтобы запустить его и увидеть отрисованный текст.

Source Code Исходный код

You can explore the source code and download the complete project directly from the GitHub repositories: Вы можете изучить исходный код и скачать готовый проект напрямую из репозиториев на GitHub:


Support My Work Поддержать проект

If these tutorials helped you, consider buying me a coffee! Если эти туториалы вам помогли, вы можете поддержать автора.

Sberbank (Russia only) Сбербанк (только для РФ)

Sberbank SBP QR Code

Direct transfer via phone number (Russia only) Перевод по номеру телефона (только для РФ)

+7 (917) 212-29-59

USDT TRC20

USDT TRC20 QR Code

Support via Cryptocurrency Поддержка криптовалютой

TMtY1YifNf6FKvgeFmqKGQR4NStKr3csGp