This is my first time using SDL.
Install SDL2 for my Linux system:
Now we can test our first SDL program.
This program is pretty simple, I want to show an image as the background of a main window.
How to compile:
g++ ../show_img.cpp -w -lSDL2 -lSDL2_image -o ./show_img
Install SDL2 for my Linux system:
sudo apt-get install libsdl2-dev libsdl2-image-dev
Now we can test our first SDL program.
This program is pretty simple, I want to show an image as the background of a main window.
- In Linux system, #include <SDL2/SDL.h> as well as #include <SDL2/SDL_image.h>
- SDL_Init(SDL_INIT_VIDEO) should be called before initializing the main window.
- Using SDL_Surface for loading image, SDL_Renderer and SDL_Texture for rendering operation.
- Free memory.
#include <iostream>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
using namespace std;
const int SCREEN_WIDTH = 800;
const int SCREEN_HEIGHT = 600;
int main( int argc, char** argv)
{
if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
{
cout << " [Error] SDL initialization fail: " << SDL_GetError() << endl;
exit(1);
}
SDL_Window* main_win = SDL_CreateWindow( "Practice_01",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
SCREEN_WIDTH,
SCREEN_HEIGHT,
SDL_WINDOW_SHOWN);
if(main_win == NULL)
{
cout << " [Error] Creating main window fail: " << SDL_GetError() << endl;
}
SDL_Event event;
SDL_Surface* bg = IMG_Load(argv[1]);
SDL_Renderer* renderer = SDL_CreateRenderer(main_win, -1, 0);
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, bg);
while(true)
{
SDL_WaitEvent(&event);
if(event.type == SDL_QUIT)
{
break;
}
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, NULL, NULL);
SDL_RenderPresent(renderer);
}
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_FreeSurface(bg);
SDL_DestroyWindow(main_win);
SDL_Quit();
return 0;
}
How to compile:
g++ ../show_img.cpp -w -lSDL2 -lSDL2_image -o ./show_img
留言
張貼留言