如何在SDL2中修改精灵大小?重制Galaga时精灵占满窗口的解决办法
解决SDL2中精灵渲染占满整个窗口的问题
问题出在你调用SDL_RenderCopy的方式上:
SDL_RenderCopy(renderer, texture, NULL, NULL);
当你把最后两个参数都设为NULL时,SDL会自动将纹理拉伸填充整个渲染目标(也就是你的窗口),这就是精灵占满屏幕的原因。
要让精灵以原尺寸(或指定尺寸)渲染,你需要定义一个SDL_Rect来指定渲染的位置和大小:
步骤1:获取纹理的实际尺寸(可选但推荐)
如果你不确定图片的实际大小,用SDL_QueryTexture获取纹理的宽高:
int texWidth, texHeight; SDL_QueryTexture(texture, NULL, NULL, &texWidth, &texHeight);
步骤2:定义目标渲染矩形
比如把精灵放在窗口底部中间,保持原尺寸:
SDL_Rect destRect; destRect.x = (WIDTH - texWidth) / 2; // 水平居中 destRect.y = HEIGHT - texHeight - 10; // 距离底部10像素 destRect.w = texWidth; // 用纹理原宽度 destRect.h = texHeight; // 用纹理原高度
如果你想强制用你定义的SPRITE_SIZE(32x32),直接把w和h设为SPRITE_SIZE即可:
destRect.w = SPRITE_SIZE; destRect.h = SPRITE_SIZE;
步骤3:修改SDL_RenderCopy调用
把最后一个参数换成你定义的矩形:
SDL_RenderCopy(renderer, texture, NULL, &destRect);
修改后的核心代码片段
替换原来的渲染部分:
/* Draw the render on window */ SDL_RenderClear(renderer); // Fill render with color // 获取纹理尺寸 int texWidth, texHeight; SDL_QueryTexture(texture, NULL, NULL, &texWidth, &texHeight); // 定义目标矩形 SDL_Rect destRect = { (WIDTH - texWidth) / 2, HEIGHT - texHeight - 10, texWidth, texHeight }; SDL_RenderCopy(renderer, texture, NULL, &destRect); // Copy the texture into render SDL_RenderPresent(renderer); // Show render on window
这样修改后,精灵就会以你指定的大小和位置渲染,不会再占满整个窗口了。
内容的提问来源于stack exchange,提问作者EnderCal1012
相关产品推荐
相关产品推荐

