SDL2双纹理视频分屏渲染问题:如何仅渲染纹理半区?
Hey there, let's get your split video stream rendering working! The core issue with your current code is that you're not specifying a source rectangle to crop the texture—you're either rendering the entire texture (using NULL for the source rect) or only adjusting where it draws to the window (the destination rect). Here's how to fix it:
Key Concept
To render only a portion of your texture, you need to define two rectangles for each video section:
- Source Rect: Which part of the texture you want to extract (e.g., left half or right half of the video buffer)
- Destination Rect: Where that extracted section should draw in your window
Step-by-Step Solution
Capture your texture's actual dimensions
First, confirm the width and height of your texture (this should match your video stream's frame size). Let's assume your texture istextureWidthpixels wide andtextureHeightpixels tall, and your window iswindowWidthxwindowHeight.Define source rectangles for left/right halves
- For the left half of the video:
SDL_Rect leftSrcRect = {0, 0, textureWidth / 2, textureHeight}; - For the right half of the video:
SDL_Rect rightSrcRect = {textureWidth / 2, 0, textureWidth / 2, textureHeight};
- For the left half of the video:
Define destination rectangles for window placement
- Draw left half to the left side of the window:
SDL_Rect leftDestRect = {0, 0, windowWidth / 2, windowHeight}; - Draw right half to the right side of the window:
SDL_Rect rightDestRect = {windowWidth / 2, 0, windowWidth / 2, windowHeight};
- Draw left half to the left side of the window:
Update and render the texture
Replace your existing render code with this (keep your texture update logic intact):// Update texture with your video buffer data SDL_UpdateTexture(texture, NULL, buffer_start, fmt.fmt.pix.width * 2); SDL_RenderClear(renderer); // Render left half of the texture to left window area SDL_RenderCopy(renderer, texture, &leftSrcRect, &leftDestRect); // Render right half of the texture to right window area SDL_RenderCopy(renderer, texture, &rightSrcRect, &rightDestRect); SDL_RenderPresent(renderer);
Additional Checks
- Double-check that
textureWidthmatches the actual width fromfmt.fmt.pix.width. Your pitch calculation (fmt.fmt.pix.width * 2) looks right for 2-byte per pixel formats like RGB565—just confirm it matches your buffer's row size. - If your texture width is odd, adjust the source rect widths (e.g.,
(textureWidth + 1)/2for the left half) to avoid missing a pixel. - Ensure your window size is set correctly so the destination rects fit without overlapping or gaps.
内容的提问来源于stack exchange,提问作者Carlos Pinto

