You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SDL中调整纹理自身尺寸?附现有渲染函数代码

调整SDL纹理自身尺寸的实现方案

你需要在现有渲染函数中添加代码,将纹理自身像素尺寸修改为dstRect指定的大小,而非仅在渲染时临时拉伸显示。以下是修改后的完整函数及说明:

void Texture::render(int x, int y, int w, int h, SDL_Renderer *&renderer, double angle, SDL_Point* center, SDL_RendererFlip flip)
{
    // 保留原有逻辑:处理默认值
    if (x < 0) { x = rect.x; }
    if (y < 0) { y = rect.y; }
    if (w < 0) { w = rect.w; }
    if (h < 0) { h = rect.h; }

    SDL_Rect dstRect = { x, y, w, h };

    // --- 新增:调整纹理自身尺寸的代码 ---
    // 仅当目标尺寸与当前纹理尺寸不一致时执行缩放
    if (w != rect.w || h != rect.h) {
        // 获取原纹理的格式与属性
        Uint32 format;
        int access;
        SDL_QueryTexture(texture, &format, &access, nullptr, nullptr);

        // 创建可作为渲染目标的新纹理,尺寸为目标大小
        SDL_Texture* scaledTexture = SDL_CreateTexture(renderer, format, SDL_TEXTUREACCESS_TARGET, w, h);
        if (!scaledTexture) {
            // 出错时打印错误信息,仍执行原有渲染逻辑避免崩溃
            printf("创建缩放纹理失败: %s\n", SDL_GetError());
            SDL_RenderCopyEx(renderer, texture, &rect, &dstRect, angle, center, flip);
            return;
        }

        // 切换渲染目标到新纹理
        SDL_SetRenderTarget(renderer, scaledTexture);
        // 清除新纹理避免残留脏数据
        SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
        SDL_RenderClear(renderer);

        // 将原纹理渲染到新纹理上,自动拉伸至目标尺寸
        SDL_Rect fullDst = { 0, 0, w, h };
        SDL_RenderCopyEx(renderer, texture, &rect, &fullDst, 0, nullptr, SDL_FLIP_NONE);

        // 恢复渲染目标为窗口
        SDL_SetRenderTarget(renderer, nullptr);

        // 替换纹理:释放旧纹理,更新成员变量
        SDL_DestroyTexture(texture);
        texture = scaledTexture;
        rect.w = w;
        rect.h = h;
    }
    // --- 新增代码结束 ---

    // 执行渲染(此时纹理已为目标尺寸,无需再用原rect裁剪)
    SDL_RenderCopyEx(renderer, texture, nullptr, &dstRect, angle, center, flip);
}

核心逻辑说明

  • 性能优化:先对比目标尺寸与当前纹理尺寸,避免重复缩放操作。
  • 纹理格式兼容:通过SDL_QueryTexture获取原纹理格式,保证新纹理与原纹理属性一致。
  • 渲染目标切换:利用SDL_SetRenderTarget将绘制目标转向新纹理,实现纹理内部的像素级缩放。
  • 资源安全:严格管理纹理内存,释放旧纹理并更新成员变量,避免内存泄漏。

内容的提问来源于stack exchange,提问作者Grant Allan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 08:45:36