Saturday, December 8, 2012

Applying transparency using win32 api, C++/SDL code




Well , lets use the win32 api - SetLayeredWindowAttributes()



#define _WIN32_WINNT 0x0500
#define WINVER 0x0500

#include <windows.h>
#include <SDL/SDL.h>
#include <SDL/SDL_syswm.h>
#include <SDL/SDL_ttf.h>
#include <SDL/SDL_image.h>
#include <iostream>
#include <string>
#include <sstream>



using namespace std;

SDL_Surface *loadimg(string filename);

int main(int argc, char* argv[])
{
    SDL_Init(SDL_INIT_EVERYTHING);
    TTF_Init();
    TTF_Font *font = TTF_OpenFont("fonts/AlphaMaleModern.ttf", 40);
    SDL_Surface *screen, *text, *img;

    screen = SDL_SetVideoMode(400, 300, 32, SDL_SWSURFACE);
    img = loadimg("images/op.png");
    SDL_SetAlpha(img, SDL_SRCALPHA, 129);

    bool running = true;
    SDL_Event events;
    Uint32 start;
    HWND hwnd;

    //transparency starts here
    SDL_SysWMinfo info;
    SDL_VERSION(&info.version);
    if(SDL_GetWMInfo(&info))
    {
        hwnd = info.window;
    }
    SetWindowLong(hwnd, GWL_EXSTYLE, GetWindowLong(hwnd, GWL_EXSTYLE) |WS_EX_LAYERED);
    SetLayeredWindowAttributes(hwnd, RGB(0,0,0), (255 * 70)/100, LWA_COLORKEY);


    Uint32 color = SDL_MapRGB(screen->format, 0x00, 0x00, 0x00);
    SDL_Color color2 = {0xff, 0xff, 0xff};

    stringstream ss;
    SDL_Rect box;
    box.x = 150;
    box.y = 130;

    SDL_Rect imgbox;
    imgbox.h = 100;
    imgbox.w = 200;
    imgbox.x = 100;
    imgbox.y = 100;

    while(running)
    {
        start = SDL_GetTicks();
        while(SDL_PollEvent(&events))
        {
            switch(events.type)
            {
                case SDL_QUIT:
                    running = false;
                    break;
            }
        }
        ss.str(" ");
        ss << "hello";
        text = TTF_RenderText_Solid(font, ss.str().c_str(), color2);

        SDL_FillRect(screen, &screen->clip_rect, color);

        SDL_BlitSurface(img, NULL, screen, &imgbox);
        //SDL_BlitSurface(text, NULL, screen, &box);
        SDL_Flip(screen);
        //frame regulation
        if(1000/30 > SDL_GetTicks() - start)
            SDL_Delay(1000/30 - (SDL_GetTicks() - start));
    }
    SDL_FreeSurface(text);
    TTF_Quit();
    SDL_Quit();
    return 0;
}


SDL_Surface *loadimg(string filename)
{
    SDL_Surface *tmp = NULL;
    SDL_Surface *opt = NULL;
    tmp = IMG_Load(filename.c_str());
    if(tmp != NULL)
    {
        SDL_SetAlpha(tmp, SDL_SRCALPHA, 129);
        opt = SDL_DisplayFormat(tmp);
        SDL_FreeSurface(tmp);
    }

    return opt;
}

1 comment:

  1. Wanted to create transparent windows and it works with your method :)

    ReplyDelete

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...