如何在C++的SDL2中解决16x16纹理像素尺寸不一致问题?
问题:SDL纹理缩放时像素尺寸不均,小尺寸下异常更明显
我的纹理所有像素尺寸不一致,且会随图像大小变化,小尺寸下该问题表现得尤为突出。我尝试过放大图像,但问题并非出在图像文件本身。
问题演示

相关代码
纹理加载函数
SDL_Texture* loadTexture(std::string path) { //The final texture SDL_Texture* newTexture = NULL; //Load image at specified path SDL_Surface* loadedSurface = IMG_Load(path.c_str()); //Create texture from surface pixels newTexture = SDL_CreateTextureFromSurface(renderer, loadedSurface); //Get rid of old loaded surface SDL_FreeSurface(loadedSurface); return newTexture; }
主函数
int main(int argc, char* args[]) { SDL_Texture* loadTexture(string path); window = SDL_CreateWindow("Euka", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED && SDL_RENDERER_PRESENTVSYNC); //Initialize renderer color SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF); //Initialize PNG loading int imgFlags = IMG_INIT_PNG; builderCreatureTexture = loadTexture("Assets/builderCreature.png"); int xPos = 200; int yPos = 200; while (running) { //Initialize renderer color SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); SDL_RenderClear(renderer); //Draw Here----- for (int x = -20; x < 20; x++) { SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); SDL_RenderClear(renderer); creature.DrawCreature(renderer, builderCreatureTexture, xPos, yPos, globalSize + x); SDL_RenderPresent(renderer); SDL_Delay(80); } //-----Draw Here SDL_RenderPresent(renderer); } }
修复方案
修正渲染器参数错误
你在创建渲染器时用了逻辑与&&,这会导致标志位被错误转换,应该用按位或|来组合渲染器属性:renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);设置纹理的最近邻缩放模式
默认的线性过滤会导致小尺寸缩放时像素模糊、尺寸不均,改成最近邻过滤可以保留像素硬边缘,避免变形。在创建纹理后添加以下代码:SDL_SetTextureScaleMode(newTexture, SDL_ScaleModeNearest);位置放在
SDL_CreateTextureFromSurface之后、SDL_FreeSurface之前。检查绘制逻辑的精度
确保DrawCreature函数中计算目标矩形时没有整数截断偏差,比如使用浮点数临时存储缩放后的尺寸,再转换为整数时做适当取整处理。
内容的提问来源于stack exchange,提问作者ItsJustLogic
相关产品推荐
相关产品推荐

