困惑于SDL_CreateRGBSurface()宽度和高度参数

时间:2016-02-10 18:31:53

标签: height width sdl rgb surface

因此,在使用SDL_CreateRGBSurface()函数的宽度和高度数字后,我真的很困惑它们是如何工作的。根据SDL Wiki,宽度和高度指的是表面的宽度和高度,但是当我说SCREENWIDTH / 2或SCREENHEIGHT / 2时,它显示的大于没有除法的情况。这是我正在搞乱的代码:

#include <iostream>
#include <SDL.h>

const int WIN_WIDTH = 640;
const int WIN_HEIGHT = 480;

int main(int argc, char **argv){
    if (SDL_Init(SDL_INIT_EVERYTHING) != 0){
        std::cerr << "SDL_Init failed: " << SDL_GetError() << "\n";
        return 1;
    }
    SDL_Window *win = SDL_CreateWindow("Rendering to a texture!", SDL_WINDOWPOS_CENTERED,
        SDL_WINDOWPOS_CENTERED, WIN_WIDTH, WIN_HEIGHT, 0);
    SDL_Renderer *renderer = SDL_CreateRenderer(win, -1,
        SDL_RENDERER_ACCELERATED | SDL_RENDERER_TARGETTEXTURE);

    SDL_Surface* s;
    SDL_Color c = { 155, 0, 0 };
    SDL_Rect r = { 0, 0, 100, 100 };
    s = SDL_CreateRGBSurface(0, WIN_WIDTH / 2, WIN_HEIGHT, 32, 0, 0, 0, 0);
    SDL_FillRect(s, &r, SDL_MapRGB(s->format, c.r, c.g, c.b));

    SDL_Texture* t;
    t = SDL_CreateTextureFromSurface(renderer, s);

    SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
    SDL_RenderClear(renderer);
    SDL_RenderCopy(renderer, t, NULL, NULL);
    SDL_RenderPresent(renderer);

    SDL_Delay(2000);
    SDL_FreeSurface(s);
    SDL_DestroyTexture(t);
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(win);
    SDL_Quit();
    return 0;
}

我真正想要的是一个宽度为100,高度为100的矩形,但为了让它在屏幕上正确显示,必须将宽度和高度指定为窗口的宽度和高度。那是为什么?

1 个答案:

答案 0 :(得分:0)

SDL_RenderCopy将拉伸源纹理以适合目标渲染器。所以它会在整个窗口上拉伸你的表面。如果要绘制100x100像素的矩形,则SDL曲面的大小应与要复制到的窗口大小相同;这样就不会发生拉伸,表面将以1:1的形式呈现。