May 292011
/* * F2IBuilder - Font to Image Builder * Example with SDL - Loading fonts generated for F2IBuilder * Exemplo com SDL - Carregando fontes geradas pelo F2IBuilder */
#include <cstdlib>
#include <string>
#include <cstdarg>
#include <SDL/SDL.h>
#include <SDL/SDL_image.h>
Uint8* pTecla = NULL;
SDL_Surface* tela = NULL;
struct FonteBitmap
{
SDL_Surface* imagem;
char largura[256];
SDL_Rect area;
};
void iniciarSDL(std::string titulo)
{
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
printf("Nao foi possivel inicializar SDL %s",SDL_GetError());
exit(-1);
} else {
tela=SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE);
if (tela) {
SDL_WM_SetCaption(titulo.c_str(),NULL);
} else {
printf("Couldn't set 640x480 video mode: %s\n",SDL_GetError());
exit(-2);
}
}
}
void finalizarSDL()
{
SDL_Quit();
}
void atualizarInput()
{
static SDL_Event event;
SDL_PollEvent(&event);
pTecla = SDL_GetKeyState(NULL);
}
bool tecla(SDLKey tecla)
{
if (pTecla[tecla]){
return true;
} else {
return false;
}
}
void carregarFonte(FonteBitmap* fonte,std::string arquivo)
{
FILE *arquivoFonte;
fonte->imagem = IMG_Load(arquivo.c_str());
std::string txt="";
if(fonte!=NULL){
txt=arquivo.substr(0,arquivo.length()-4);
txt+=".dat";
arquivoFonte = fopen(txt.c_str(),"rb");
if (arquivoFonte!=NULL){
fread(&fonte->largura, 256, 1, arquivoFonte);
fclose(arquivoFonte);
} else {
for (int l=0;l<256;l++){
fonte->largura[l] = fonte->imagem->w/16;
}
}
fonte->area.w=fonte->imagem->w/16;
fonte->area.h=fonte->imagem->h/16;
}
}
void descarregarFonte(FonteBitmap* fonte)
{
if (fonte->imagem){
SDL_FreeSurface(fonte->imagem);
}
}
void escreverFonte(FonteBitmap* fonte, int X, int Y, const char* PALAVRA)
{
int i,t=strlen(PALAVRA);
unsigned char l;
SDL_Rect posicao;
SDL_Rect tamanho;
posicao.x=X;
posicao.y=Y;
for (i=0; i<t; i++){
l=PALAVRA[i];
tamanho.x=(l%16)*fonte->area.w; tamanho.w=fonte->largura[l];
tamanho.y=(l/16)*fonte->area.h; tamanho.h=fonte->area.h;
SDL_BlitSurface(fonte->imagem, &tamanho , tela, &posicao);
posicao.y=Y;
posicao.x=posicao.x+fonte->largura[l];
}
}
void escreverFonteMelhorada(FonteBitmap* fonte, int X, int Y, const char* TEXTO, ...)
{
char texto_aux[256];
va_list ap;
va_start(ap, TEXTO);
vsprintf(texto_aux, TEXTO, ap);
va_end(ap);
escreverFonte(fonte,X,Y,texto_aux);
}
int main(int argc, char *argv[])
{
bool continuarLoop = true;
iniciarSDL("F2IBuilder - Exemplo C++");
FonteBitmap fonteBitmap;
carregarFonte(&fonteBitmap,"fonte.png");
while(continuarLoop) {
atualizarInput();
SDL_FillRect(tela, NULL, 700);
escreverFonteMelhorada(&fonteBitmap,10,0,"F2IBuilder");
escreverFonteMelhorada(&fonteBitmap,100,150,"Number:%d",10);
escreverFonteMelhorada(&fonteBitmap,300,260,"PJMOO");
escreverFonteMelhorada(&fonteBitmap,10,360,"Exemplo - Example");
if (tecla(SDLK_ESCAPE)){
continuarLoop = false;
}
SDL_Flip(tela);
}
descarregarFonte(&fonteBitmap);
finalizarSDL();
return 0;
}





