SDL2.0_06_text

来源:互联网 发布:如何自学java 编辑:程序博客网 时间:2024/05/17 23:03

使用了SDL_ttf扩展库,字体文件*.ttf可以在Sourceforge上下载。

#include <iostream>#include <windows.h>#include <string>using namespace std;#include <SDL.h>#include <SDL_image.h>#include <SDL_ttf.h>const int SCREEN_WIDTH = 640;const int SCREEN_HEIGHT = 480;void renderTexture(SDL_Texture *tex, SDL_Renderer *ren, SDL_Rect dst, SDL_Rect *clip = nullptr) {SDL_RenderCopy(ren, tex, clip, &dst);}void renderTexture(SDL_Texture *tex, SDL_Renderer *ren, int x, int y, SDL_Rect *clip = nullptr) {SDL_Rect dst;dst.x = x;dst.y = y;if (clip != nullptr) {dst.w = clip->w;dst.h = clip->h;}else SDL_QueryTexture(tex, NULL, NULL, &dst.w, &dst.h);renderTexture(tex, ren, dst, clip);}SDL_Texture *renderText(const string &message, const string &fontFile, SDL_Color color, int fontSize, SDL_Renderer *ren) {TTF_Font *font = TTF_OpenFont(fontFile.c_str(), fontSize);if (font == nullptr) {cout << "Failed to open font..." << endl;exit(0);}SDL_Surface *surf = TTF_RenderText_Blended(font, message.c_str(), color);SDL_Texture *tex = SDL_CreateTextureFromSurface(ren, surf);SDL_FreeSurface(surf);TTF_CloseFont(font);return tex;}int main(int argc, char** argv){if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {cout << SDL_GetError() << endl;return 0;}if (TTF_Init() == -1) {cout << TTF_GetError() << endl;return 0;}SDL_Window *win = nullptr;win = SDL_CreateWindow("05:", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_RESIZABLE);if (win == nullptr) {cout << SDL_GetError() << endl;return 0;}SDL_Renderer *ren = nullptr;ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);if (ren == nullptr) {cout << SDL_GetError() << endl;return 0;}SDL_Color color = { 128, 128, 128 };SDL_Texture *bg = renderText("Why I have to learn SDL?", "chivo-black-webfont.ttf", color, 64, ren);if (bg == nullptr) {cout << "Could not load font correctly!" << endl;return 0;}SDL_RenderClear(ren);int bw, bh;SDL_QueryTexture(bg, NULL, NULL, &bw, &bh);SDL_Event e;bool quit = false;while (!quit) {while (SDL_PollEvent(&e)){if (e.type == SDL_QUIT) {cout << "quit..." << endl;quit = true;}if (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE) {quit = true;}}SDL_RenderClear(ren);renderTexture(bg, ren, SCREEN_WIDTH/2 - bw/2, SCREEN_HEIGHT/2 - bh/2);SDL_RenderPresent(ren);}SDL_DestroyTexture(bg);SDL_DestroyRenderer(ren);SDL_DestroyWindow(win);SDL_Quit();IMG_Quit();cout << "Success!" << endl;return 0;}

 

 

0 0
原创粉丝点击