一、现象:
wchar_t wcText[1024] = { L"计算机" };
SDL_Surface *surface_font = TTF_RenderUNICODE_Solid(m_font, (Uint16*)wcText, textColor);
只显示了第一个汉字:
二、选择了一种比较挫的解决办法:
#include <QCoreApplication>
#include "include/SDL.h"
#include "include/SDL_ttf.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
TTF_Init();
TTF_Font *m_font = TTF_OpenFont("/usr/share/fonts/opentype/noto/NotoSerifCJK-Black.ttc", 100);
if (!m_font){
return 0;
}
//
SDL_Init(SDL_INIT_EVERYTHING);//SDL初始化
SDL_Window *Screen = SDL_CreateWindow("Title", 100, 100, 640, 480, SDL_WINDOW_RESIZABLE);//创建窗口
SDL_Renderer *render = SDL_CreateRenderer(Screen, -1, 0);//创建渲染器
//
SDL_Color textColor = { 255, 255, 255 };
wchar_t wcText[1024] = { L"计算机" };
//
std::vector<int>vWidth;
std::vector<SDL_Surface*>vSurface;
std::vector<SDL_Texture*>vTexture;
for(int i = 0; i < wcslen(wcText); i++){
wchar_t wcData[1024] = {0};
wcData[0] = wcText[i];
SDL_Surface *surface_font = TTF_RenderUNICODE_Solid(m_font, (Uint16*)wcData, textColor);
if(surface_font != NULL){
SDL_Texture *texture_font = SDL_CreateTextureFromSurface(render, surface_font);
if(texture_font != NULL){
int nWidth = 0;
int nHeight = 0;
if(TTF_SizeUNICODE(m_font, (Uint16*)wcData, &nWidth, &nHeight) == 0){//计算每个字符的宽度
vWidth.push_back(nWidth);
vSurface.push_back(surface_font);
vTexture.push_back(texture_font);
}
else{
SDL_FreeSurface(surface_font);
SDL_DestroyTexture(texture_font);
}
}
else{
SDL_FreeSurface(surface_font);
}
}
}
//
SDL_RenderClear(render);
//
for(int i = 0; i < vTexture.size(); i++){
long nTotal = 0;
for(int j = 0; j < i; j++){
nTotal += vWidth.at(j);
}
SDL_Rect rect_Font;//字体在哪里输出
rect_Font.x = 200 + nTotal;//计算每个字符从起始点有多少偏移量
rect_Font.y = 100;
rect_Font.w = vWidth.at(i);//每个字符本身宽度
rect_Font.h = 100;
SDL_RenderCopy(render, vTexture[i], NULL, &rect_Font);//拷贝字体数据
}
//
SDL_RenderPresent(render);
//
SDL_Event event;
while (1){
SDL_PollEvent(&event);
if (event.type == SDL_QUIT){
break;
}
}
for(int i = 0; i < vSurface.size(); i++){
SDL_FreeSurface(vSurface.at(i));//释放字体
}
vSurface.clear();
for(int i = 0; i < vTexture.size(); i++){
SDL_DestroyTexture(vTexture.at(i));//释放纹理
}
vTexture.clear();
SDL_DestroyRenderer(render);//释放渲染器
SDL_DestroyWindow(Screen);//销毁窗口
TTF_CloseFont(m_font);//释放字体资源
TTF_Quit();
SDL_Quit();//退出
return a.exec();
}
显示结果: