2013-09-01 64 views
-1

我试图做一个简单的图像查看器。我基本上加载一个图像到一个表面,然后从它创建一个纹理。SDL2与操纵像素和SDL_UpdateTexture混淆图像

最后,我按照migration guide的惯例做了通常的SDL_RenderClear(),SDL_RenderCopy()SDL_RenderPresent()

这工作得很好,但如果我拨打以上SDL_UpdateTexture()前3渲染电话,我得到一个混乱的图像:

Messed up image

我打电话SDL_UpdateTexture()这样的:

SDL_UpdateTexture(texture, NULL, image->pixels, image->pitch) 

其中image是我为图像加载的表面,texture是我从中创建的纹理。尝试改变音调的结果会导致不同的混乱图像。我也尝试使用rect作为第二个参数,但如果rect与图像的尺寸相同,则结果相同。如果尺寸较大(例如与窗口相同),则更新不会发生,但没有错误。

full code可用。

我想通过image->pixels直接操作表面的像素,然后拨打SDL_UpdateTexture(),但只是调用SDL_UpdateTexture()而没有任何篡改就足以搞砸了。

回答

0

你可以试试以下内容。它应该将任何粉色(r = 255,g = 0,b = 255)像素替换为透明。您只需更改pixel32操作以适应您的需求。

SDL_Surface* image = IMG_Load(filename); 

SDL_Surface* imageFomatted = SDL_ConvertSurfaceFormat(image, 
                 SDL_PIXELFORMAT_RGBA8888, 
                 NULL); 

texture = SDL_CreateTexture(renderer, 
          SDL_PIXELFORMAT_RGBA8888, 
          SDL_TEXTUREACCESS_STREAMING, 
          imageFomatted->w, imageFomatted->h); 

void* pixels = NULL; 
int pitch = 0; 

SDL_LockTexture(texture, &imageFomatted->clip_rect, &pixels, &pitch); 

memcpy(pixels, imageFomatted->pixels, (imageFomatted->pitch * imageFomatted->h)); 

int width = imageFomatted->w; 
int height = imageFomatted->h; 

Uint32* pixels32 = (Uint32*)pixels; 
int  pixelCount = (pitch/4) * height; 

Uint32 colorKey  = SDL_MapRGB(imageFomatted->format, 0xFF, 0x00, 0xFF); 
Uint32 transparent = SDL_MapRGBA(imageFomatted->format, 0xFF, 0x00, 0xFF, 0x00); 

for (int i = 0; i < pixelCount; i++) { 
    if (pixels32[i] == colorKey) { 
    pixels32[i] = transparent; 
    } 
} 

SDL_UnlockTexture(texture); 

SDL_FreeSurface(imageFormatted); 
SDL_FreeSurface(image); 

pixels = NULL; 
pitch = 0; 
width = 0; 
height = 0; 
+0

谢谢您的回答。这是memcpy上的焦点,但运行时,如果你替换image-> pitch只是音调。由于formattedSurf没有在任何地方定义,我从colorKey行注释到for循环结束。我似乎无法使用像素没有崩溃的程序。 – Gigi

+0

@Gigi对不起,我犯了一些错误,因为我正在调整我的代码以适应你的错误,所以错过了一些变量名。你能否再次尝试完整的代码(包括memcopy),我认为这可能是由于在创建纹理之前不转换表面格式,所以我添加了这个。 – Zammalad

+0

您错过了纹理的声明,并且在imageFormatted中有一个拼写错误(缺少'r') - 所以SDL_FreeSurface(imageFormatted)不一致。修复这些后,我仍然在memcpy上崩溃。你可以尝试在发布之前测试代码吗? – Gigi

1

我觉得有些不对的间距或SDL_Rect参数, 但还有另外一个SDL功能,可以帮助:

SDL_Texture* SDL_CreateTextureFromSurface(SDL_Renderer* renderer, 
             SDL_Surface* surface)