2013-09-01 162 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)