SDL2使用单独线程来绘制时绘制的东西大小会自动随窗口大小改变,怎么回事?

代码

#include<stdbool.h>
#include<SDL2/SDL.h>
const int FPS=60;
const char*title="Test";
int width=640,height=480;
bool isRun;
SDL_Window*win=NULL;
SDL_Renderer*ren=NULL;
bool initSDL(){
    if(SDL_Init(SDL_INIT_VIDEO)!=0){
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,"SDL2 init error:%s",SDL_GetError());
        return false;
    }
    return true;
}
void quit(){
    if(ren!=NULL){
        SDL_DestroyRenderer(ren);
    }
    if(win!=NULL){
        SDL_DestroyWindow(win);
    }
    SDL_Quit();
}
bool createSDL(){
    win=SDL_CreateWindow(title,SDL_WINDOWPOS_UNDEFINED,SDL_WINDOWPOS_UNDEFINED,width,height,SDL_WINDOW_SHOWN|SDL_WINDOW_RESIZABLE);
    if(win==NULL){
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,"SDL2 create window error:%s",SDL_GetError());
        return false;
    }
    ren=SDL_CreateRenderer(win,-1,SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC);
    if(ren==NULL){
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,"SDL2 create window error:%s",SDL_GetError());
        return false;
    }
    return true;
}
void render(){
    /*背景颜色*/
    SDL_SetRenderDrawColor(ren,18,18,18,0xFF);
    SDL_RenderClear(ren);
    /*画正方形*/
    SDL_SetRenderDrawColor(ren,0xFF,0,0,0xFF);
    SDL_Rect rt={(width-100)/2,(height-100)/2,100,100};/*奇怪,我宽和高都是100,怎么在改变窗口大小时宽高也会改变?*/
    SDL_RenderFillRect(ren,&rt);
    SDL_RenderPresent(ren);
}
/*绘制线程*/
int drawing(void*data){
    unsigned long long start;
    int waitTime;
    while(isRun){
        /*控制帧率*/
        start=SDL_GetPerformanceCounter();
        render();
        waitTime=1000/FPS-(SDL_GetPerformanceCounter()-start)*1000/SDL_GetPerformanceFrequency();
        if(waitTime<0 || waitTime>=500){
            waitTime=1000/FPS;
        }
        SDL_Delay(waitTime);
    }
    return 0;
}
void handleEvent(){
    SDL_Event event;
    SDL_WaitEvent(&event);
    if(true){
        switch(event.type){
        case SDL_QUIT:
            isRun=false;
            break;
        case SDL_WINDOWEVENT:
            switch(event.window.event){
            case SDL_WINDOWEVENT_SIZE_CHANGED:
                SDL_GetWindowSize(win,&width,&height);
                SDL_Log("size change to %d,%d\n",width,height);
                break;
            case SDL_WINDOWEVENT_RESIZED:
                width=event.window.data1;
                height=event.window.data2;
                SDL_Log("resize to %d,%d\n",width,height);
                break;
            default:
                break;
            }
        default:
            break;
        }
    }
}
int main(int argc,char**argv){
    if(!initSDL()){
        return 1;
    }
    isRun=createSDL();
    SDL_Thread*th=SDL_CreateThread(drawing,"drawing",NULL);
    while(isRun){
        handleEvent();
    }
    SDL_WaitThread(th,NULL);
    quit();
    return 0;
}

运行结果

图片说明
为什么会这样?如果我要固定正方形的大小该怎么做?

1个回答

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐