Monday, December 7, 2015

HOW TO LOAD PNG IMAGE AND DISPLAY IT TO SCREEN USING SDL

Hey fellas! Now, I want to explain you about SDL. SDL is Simple DirectMedia Layer. SDL is a cross-platform development library designed to provide low level access to audio, keyboard, mouse, joystick, and graphics hardware via OpenGL and Direct3D. SDL officially supports Windows, Mac OS X, Linux, iOS, and Android. Support for the other platforms may be found in the source code. SDL is written in C, works natively with C++, and there are bindings available for several other languages, including C# and Python.
And now, I will explain about HOW TO LOAD PNG IMAGE AND DISPLAY IT TO SCREEN USING SDL.

 Here, I'm using SDL2. In SDL2, we can load image using the SDL_LoadBMP() function. But, unfortunately, that function doesnt provide us to work with the other image formats. However, such functionality is provided by an extension library called SDL_image.

First, make a new project. And don't forget to add the location of library and includepath to the .pro file. Because we use library SDL_image, so don't forget to put -lSDL2_image after the location of the library.



After that, let's go to the source code~~
oiya, don't forget to place the image in your Debug folder, where your executable is located.
This is the source code, if u want to load the png image and display it to the screen.


#include<SDL2/SDL.h>
#include<SDL2/SDL_image.h>

int main(int argc, char** argv)
{
    bool quit = false;
    SDL_Event event;

    SDL_Init(SDL_INIT_VIDEO);
    IMG_Init(IMG_INIT_PNG);

    SDL_Window * window = SDL_CreateWindow("SDL2 Displaying Image PNG",
        SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0);

    SDL_Renderer * renderer = SDL_CreateRenderer(window, -1, 0);
    SDL_Surface * image = IMG_Load("IMG_4457.png");
    SDL_Texture * texture = SDL_CreateTextureFromSurface(renderer, image);

    while (!quit)
    {
        SDL_WaitEvent(&event);

        switch (event.type)
        {
            case SDL_QUIT:
                quit = true;
                break;
        }
        SDL_RenderCopy(renderer, texture, NULL, NULL);
        SDL_RenderPresent(renderer);
    }

    SDL_DestroyTexture(texture);
    SDL_FreeSurface(image);
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);

    IMG_Quit();
    SDL_Quit();

    return 0;
}



and when we compile it, the picture will appear in the new window with name "SDL2 Displaying Image PNG".

Okay, that's all from me. Now, it's your turn to try this with your own laptop or pc wkwkwk
As usually, have a great time with coding!


No comments:

Post a Comment