c - 为什么我不能对 SDL 纹理使用 colorkey?

标签 c sdl sprite color-key

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

知道发生了什么事或如何解决它吗?这是用 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 中的错误造成的,我最终为此提交了补丁。

最佳答案

这里有两个示例可能会对您有所帮助。它们在 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));
}

关于c - 为什么我不能对 SDL 纹理使用 colorkey?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1114633/

相关文章:

java - 如何在Android版Cocos2d中复制CCSprite?

c++ - D3DXMatrixTransformation2D 行为怪异

c++ - 为什么 C/C++ 中允许单独使用分号?

c - ENOSPC vs ENOMEM 什么时候使用?

c getaddrinfo 没有这样的主机是已知的

c++ - 使用 Alpha channel 复制 SDL_Surfaces

c++ - 在另一台计算机上运行代码时找不到内容(图像/声音)c++

linux - 启用垂直同步时出现断断续续的 SDL+OpenGL 动画

java - LibGDX 1.5 围绕其中心旋转 Sprite

c - 为什么 gid_t 不在我的 sys/types 头文件中?