SDL
Using metrics in Language C with the SDL library
/*
* F2IBuilder - Font to Image Builder
* Example with SDL - Loading fonts generated for F2IBuilder
* Exemplo com SDL - Carregando fonts geradas pelo F2IBuilder
*/
#include <cstdlib>
#include <string>
#include <cstdarg>
#include <SDL/SDL.h>
#include <SDL/SDL_image.h>
Uint8* pKey = NULL;
SDL_Surface* screen = NULL;
struct fontBitmap
{
SDL_Surface* image;
char largura[256];
SDL_Rect area;
};
void initSDL(std::string title)
{
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
printf("Nao foi possivel inicializar SDL %s",SDL_GetError());
exit(-1);
} else {
screen=SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE);
if (screen) {
SDL_WM_SetCaption(title.c_str(),NULL);
} else {
printf("Couldn't set 640x480 video mode: %s\n",SDL_GetError());
exit(-2);
}
}
}
void shutdownSDL()
{
SDL_Quit();
}
void updateInput()
{
static SDL_Event event;
SDL_PollEvent(&event);
pKey = SDL_GetKeyState(NULL);
}
bool key(SDLKey key)
{
if (pKey[key]){
return true;
} else {
return false;
}
}
void loadFont(fontBitmap* font,std::string filename)
{
FILE *fileFont;
font->image = IMG_Load(filename.c_str());
std::string txt="";
if(font!=NULL){
txt=filename.substr(0,filename.length()-4);
txt+=".dat";
fileFont = fopen(txt.c_str(),"rb");
if (fileFont!=NULL){
fread(&font->largura, 256, 1, fileFont);
fclose(fileFont);
} else {
for (int l=0;l<256;l++){
font->largura[l] = font->image->w/16;
}
}
font->area.w=font->image->w/16;
font->area.h=font->image->h/16;
}
}
void unloadFont(fontBitmap* font)
{
if (font->image){
SDL_FreeSurface(font->image);
}
}
void writeFont(fontBitmap* font, int X, int Y, const char* WORD)
{
int i,t=strlen(WORD);
unsigned char l;
SDL_Rect position;
SDL_Rect size;
position.x=X;
position.y=Y;
for (i=0; i<t; i++){
l=WORD[i];
size.x=(l%16)*font->area.w; size.w=font->largura[l];
size.y=(l/16)*font->area.h; size.h=font->area.h;
SDL_BlitSurface(font->image, &size , screen, &position);
position.y=Y;
position.x=position.x+font->largura[l];
}
}
void writeImprovedFont(fontBitmap* font, int X, int Y, const char* TEXT, ...)
{
char texto_aux[256];
va_list ap;
va_start(ap, TEXT);
vsprintf(texto_aux, TEXT, ap);
va_end(ap);
writeFont(font,X,Y,texto_aux);
}
int main(int argc, char *argv[])
{
bool loop = true;
initSDL("F2IBuilder - Exemplo C++");
fontBitmap fontBitmap;
loadFont(&fontBitmap,"font.png");
while(loop) {
updateInput();
SDL_FillRect(screen, NULL, 700);
writeImprovedFont(&fontBitmap,10,0,"F2IBuilder");
writeImprovedFont(&fontBitmap,100,150,"Number:%d",10);
writeImprovedFont(&fontBitmap,300,260,"PJMOO");
writeImprovedFont(&fontBitmap,10,360,"Exemplo - Example");
if (key(SDLK_ESCAPE)){
loop = false;
}
SDL_Flip(screen);
}
unloadFont(&fontBitmap);
shutdownSDL();
return 0;
}
