Saturday, October 27, 2012

Draw a graph using SDL/C++

Drawing a graph on an x, y plane... you can disregard the load image function, remember i am using the sdl_draw.h library, which is freely available on the sdl website, but you can also implement the draw line and draw pixel function  yourself. This program is helpful in making a real time graph, just like the one you see on windows task manager under performance tab.

#include <iostream>
#include <string>
#include <deque>
#include <SDL/SDL.h>
#include <SDL/SDL_draw.h>
#include <SDL/SDL_image.h>
using namespace std;


void DrawGraph(SDL_Surface* screen, deque<int> *d);
SDL_Surface* load_image(string file);

int main(int argc, char* argv[])
{
    SDL_Init(SDL_INIT_EVERYTHING);
    SDL_Surface* screen, *bgimg;
    screen = SDL_SetVideoMode(400, 350, 32, SDL_SWSURFACE);
    bgimg = load_image("border.png");
    SDL_Event events;
    SDL_Rect box;
    box.x = 100;
    box.y = 150;
    box.h = 100;
    box.w = 205;
    Uint32 start;
    bool running = true;

    int value[] = {49, 68, 55, 66, 39, 40, 79, 23};
    deque<int> d(value, value + sizeof(value)/sizeof(int));
    deque<int>::iterator it;


    while(running)
    {
        start = SDL_GetTicks();
        while(SDL_PollEvent(&events))
        {
            switch(events.type)
            {
                case SDL_QUIT:
                    running = false;
                    break;
            }
        }
        //logic

        DrawGraph(screen, &d);
        SDL_BlitSurface(bgimg, NULL, screen, &box);
        //render
        SDL_Flip(screen);
        if(1000/30 > SDL_GetTicks() - start)
            SDL_Delay(1000/30 - (SDL_GetTicks() - start));
    }

    SDL_Quit();
    return 0;
}

void DrawGraph(SDL_Surface* screen, deque<int> *d)
{
    Uint32 color = SDL_MapRGB(screen->format, 0xff, 0xbc, 0x00);
    deque<int>::iterator it;
    int i;
    for(it = d->begin(), i = 150; it != d->end(); i+=5, it++)
    {
        if(it == d->begin())
            Draw_Pixel(screen, i, *it, color);
        else
            Draw_Line(screen, i-5,*(it -1), i, *it, color);
    }


}

SDL_Surface* load_image(string file)
{
    SDL_Surface* tmp=NULL;
    SDL_Surface* img=NULL;

    img = IMG_Load(file.c_str());
    if(img != NULL)
    {
        tmp = SDL_DisplayFormat(img);
        SDL_FreeSurface(img);
    }
    return tmp;
}

No comments:

Post a Comment

How to create Custom push button in QT5

To be honest this is not my work its an exact copy from this link. http://mcmtechtips.blogspot.com/2012/03/shape-qpushbutton-in-your-own-st...