Problems with SDL_SetColorKey

时间秒杀一切 提交于 2019-12-11 23:41:55

问题


I'm trying to create a transparent sprite with SDL. I'm using SDL_SetColorKey on a bitmap with magenta (0xff00ff) background (it's 100% magenta, I checked it with the GIMP :)) The call to SDL_SetColorKey looks like this:

SDL_SetColorKey( bitmap, SDL_SRCCOLORKEY, SDL_MapRGB(bitmap->format, 255, 0, 255) );

The call to SDL_SetColorKey apparently returns 0, however there is no transparency. Can anyone tell me what I am missing here?

Here is the problematic code in case anyone wants to test it:

#include "SDL/SDL.h"

const int WINDOW_WIDTH = 640;
const int WINDOW_HEIGHT = 480;
const char* WINDOW_TITLE = "SDL Start";

int main(int argc, char **argv)
{
   SDL_Init( SDL_INIT_VIDEO );

   SDL_Surface* screen = SDL_SetVideoMode( WINDOW_WIDTH, WINDOW_HEIGHT, 0, 
      SDL_HWSURFACE | SDL_DOUBLEBUF );
   SDL_WM_SetCaption( WINDOW_TITLE, 0 );

   SDL_Surface* bitmap = SDL_LoadBMP("resources/ship.bmp");
   if(SDL_SetColorKey( bitmap, SDL_SRCCOLORKEY, SDL_MapRGB(bitmap->format, 255, 0, 255) )) printf("aaaaa %s", SDL_GetError());



   // Part of the screen we want to draw the sprite to
   SDL_Rect destination;
   destination.x = 100;
   destination.y = 100;
   destination.w = 65;
   destination.h = 44;

   SDL_Event event;
   bool gameRunning = true;

   while (gameRunning)
   {
      if (SDL_PollEvent(&event))
      { 
         if (event.type == SDL_QUIT)
         {
            gameRunning = false;
         }
      }

      SDL_BlitSurface(bitmap, NULL, screen, &destination);

      SDL_Flip(screen);
   }

   SDL_FreeSurface(bitmap);

   SDL_Quit();

   return 0;
}

UPDATE: In case anyone needs it, here is the bitmap: http://dl.dropbox.com/u/8936880/ship.bmp


回答1:


The problem is with your image, i used one generated by me and it works out of the box with your code.

Your image is in 32 bits and it seems that SDL_SetColorKey doesn't like it, convert it to 24 bits and it should work.

You can convert it with Gimp when you save it to BMP from the advanced settings.

Try with this one converted to 24 bits.



来源:https://stackoverflow.com/questions/4973551/problems-with-sdl-setcolorkey

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!