为什么我不能将colorkey用于SDL纹理?

时间:2009-07-11 21:03:14

标签: c sdl sprite color-key

我编写了这个简单的C程序来测试基本的SDL 1.3功能。一切正常,只有一个小问题。 colorkey不会被转换。我正在加载一个8位PNG精灵文件,其中调色板索引#0是背景颜色。我希望看到只显示精灵,但我得到的是整个图像,包括背景颜色。

知道发生了什么或如何修复它?这是用Visual C ++ 2005编写的。

// SDL test.c : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "sdl.h"
#include "sdl_image.h"
#include <stdio.h>

int _tmain(int argc, _TCHAR* argv[])
{
    int windowID;
    int textureID;
    SDL_Surface* surface;
    char* dummy = "";
    SDL_Color color;

    SDL_Init(SDL_INIT_VIDEO);

    windowID = SDL_CreateWindow("SDL Test", 400, 400, 320, 240, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
    if (windowID == 0)
    {
        printf("Unable to create window: %s\n", SDL_GetError());
    }
    else printf("Window created: %d\n", windowID);

    if (SDL_CreateRenderer(windowID, -1, SDL_RENDERER_PRESENTFLIP2) != 0)
    {
        printf("Unable to create renderer: %s\n", SDL_GetError());
    }
    else printf("Renderer created successfully.\n");

    if (SDL_SelectRenderer(windowID) != 0)
    {
        printf("Unable to select renderer: %s\n", SDL_GetError());
    }
    else printf("Renderer selected successfully\n");

    SDL_RenderPresent();

    surface = IMG_Load("<INSERT FILENAME HERE>");
    if (!surface)
    {
        printf("Unable to load image!\n");
    }
    else printf("Image Loaded\n");

    color = surface->format->palette->colors[0];
    SDL_SetColorKey(surface, 1, SDL_MapRGB(surface->format, color.r, color.g, color.b));

    textureID = SDL_CreateTextureFromSurface(0, surface);
    if (textureID == 0)
    {
        printf("Unable to create texture: %s\n", SDL_GetError());
    }
    else printf("Texture created: %d\n", textureID);

    SDL_FreeSurface(surface);

    if (SDL_RenderCopy(textureID, NULL, NULL) != 0)
    {
        printf("Unable to render texture: %s", SDL_GetError());
    }

    SDL_RenderPresent();

    scanf_s("%s", dummy);
    return 0;
}

编辑:结果是由于SDL_CreateTextureFromSurface中的一个错误,我最终提交了一个补丁。

2 个答案:

答案 0 :(得分:2)

以下是两个可能对您有用的示例。使用SDL1.3,它们对我来说非常适合。

if (color == white)
{
    SDL_SetColorKey(bmp_surface, 1,
                    SDL_MapRGB(bmp_surface->format, 255, 255, 255));
}

if (color == blue)
{
    SDL_SetColorKey(bmp_surface, 1,
                    SDL_MapRGB(bmp_surface->format, 0, 0, 254));
}

答案 1 :(得分:0)

您应该在使用前将曲面转换为显示格式。

...
surface = IMG_Load("<INSERT FILENAME HERE>");
SDL_DisplayFormat(surface);
SDL_SetColorKey(surface, 1, SDL_MapRGB(surface->format, color.r, color.g, color.b));
...

这样做总是一个好主意,因此您绝对可以确保所有图像具有相同的格式,并在使用SDL功能时提供正确的结果。

虽然我只熟悉1.2版本,但不知道1.3中的内容有什么变化。