C++ SDL_ttf文字显示

C++ SDL_ttf文字显示

配置请参照前面的笔记https://www.cnblogs.com/zzr-stdio/p/14514043.html

需要下载配置SDL_ttf,下载地址:http://www.libsdl.org/projects/SDL_ttf/,配置过程与SDL_image类似。

示例程序:

#include <iostream>
#include<SDL.h>
#include<SDL_image.h>
#include<SDL_mixer.h>
#include<SDL_ttf.h>
#include<vector>
using namespace std;
const int WIDTH = 800;
const int HEIGHT = 600;
int main(int argc, char* argv[])
{
    ::SDL_Init(SDL_INIT_VIDEO);//初始化SDL
    ::SDL_Window* window = ::SDL_CreateWindow("SDL test", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
        WIDTH, HEIGHT, SDL_WINDOW_SHOWN);//创建窗体
    ::SDL_Renderer* rend = ::SDL_CreateRenderer(window, -1, 0);
    ::TTF_Init();//初始化字库
    ::TTF_Font* font = ::TTF_OpenFont("simhei.ttf", 60);//打开字库
    ::SDL_Color red = { 255, 0, 0 };//文字颜色
    ::SDL_Surface* text = ::TTF_RenderUTF8_Blended(font, "hello", red);
    ::SDL_Texture* texture = ::SDL_CreateTextureFromSurface(rend, text);
    ::SDL_Rect textrect = { 0, 0, text->w, text->h };
    bool quit = false;
    ::SDL_Event event;
    while (quit == false)
    {
        while (::SDL_PollEvent(&event))
        {
            if (event.type == SDL_QUIT)
            {
                quit = true;
            }
            else if (event.type == SDL_MOUSEBUTTONDOWN)
            {
                
            }
            else if (event.type == SDL_KEYDOWN)
            {
                switch (event.key.keysym.sym)//键盘的上下左右控制文字显示位置
                {
                case SDLK_LEFT:
                    textrect.x -= 10;
                    break;
                case SDLK_RIGHT:
                    textrect.x += 10;
                    break;
                case SDLK_UP:
                    textrect.y -= 10;
                    break;
                case SDLK_DOWN:
                    textrect.y += 10;
                    break;
                }
            }
        }
        ::SDL_RenderClear(rend);
        
        ::SDL_RenderCopy(rend, texture, nullptr, &textrect);
        ::SDL_RenderPresent(rend);
    }
    ::SDL_DestroyRenderer(rend);
    ::SDL_DestroyWindow(window);//销毁窗体
    ::SDL_Quit();//退出SDL
    return 0;
}


原文地址:https://www.cnblogs.com/zzr-stdio/p/14514689.html