gpt4 book ai didi

c++ - SDL2不使用纹理绘制图像

转载 作者:搜寻专家 更新时间:2023-10-31 01:45:03 26 4
gpt4 key购买 nike

我一直在尝试创建一个简单的 SDL2 程序来显示图像然后退出。我有这段代码:

/* compile with `gcc -lSDL2 -o main main.c` */

#include <SDL2/SDL.h>
#include <SDL2/SDL_video.h>
#include <SDL2/SDL_render.h>
#include <SDL2/SDL_surface.h>
#include <SDL2/SDL_timer.h>

int main(void){
SDL_Init(SDL_INIT_VIDEO);
SDL_Window * w = SDL_CreateWindow("Hi", 0, 0, 640, 480, 0);
SDL_Renderer * r = SDL_CreateRenderer(w, -1, 0);

SDL_Surface * s = SDL_LoadBMP("../test.bmp");
SDL_Texture * t = SDL_CreateTextureFromSurface(r, s);
SDL_FreeSurface(s);

SDL_RenderClear(r);
SDL_RenderCopy(r, t, 0, 0);
SDL_RenderPresent(r);

SDL_Delay(2000);

SDL_DestroyTexture(t);
SDL_DestroyRenderer(r);
SDL_DestroyWindow(w);

SDL_Quit();
}

我知道我省略了每个函数成功的正常检查——它们都成功了,为了便于阅读,它们被删除了。我也知道我使用了 0 而不是空指针或正确的枚举值,这也不是问题的原因(因为当我正确构建程序时会发生同样的问题,这是一个快速测试用例来测试最简单的情况)

目的是出现一个窗口并显示图像(肯定在该目录中),等待几秒钟然后退出。然而,结果是窗口正确显示,但窗口被黑色填充。

额外的注释 SDL_ShowSimpleMessageBox() 似乎可以正常工作。不过,我不知道这与框架的其余部分有什么关系。

最佳答案

我会澄清这一点,你想制作一个纹理,直接做是为了便于控制,另外这可以让你更好地控制图像,尝试使用这段代码,经过全面测试,并且可以工作,你想要的只是显示图像并在 2 秒内关闭的窗口对吗?如果图片未加载,则它是您图片的位置。

/* compile with `gcc -lSDL2 -o main main.c` */

#include <SDL.h>
#include <SDL_image.h>
#include <iostream> //I included it since I used cout


int main(int argc, char* argv[]){
bool off = false;
int time;

SDL_Init(SDL_INIT_VIDEO);
SDL_Window * w = SDL_CreateWindow("Hi", 0, 0, 640, 480, SDL_WINDOW_SHOWN);
SDL_Renderer * r = SDL_CreateRenderer(w, -1, SDL_RENDERER_ACCELERATED);

SDL_Texture * s = NULL;
s = IMG_LoadTexture(r, "../test.bmp"); // LOADS A TEXTURE DIRECTLY FROM THE IMAGE
if (s == NULL)
{
cout << "FAILED TO FIND THE IMAGE" << endl; //we did this to check if IMG_LoadTexture found the image, if it showed this message in the cmd window (the black system-like one) then it means that the image can't be found
}
SDL_Rect s_rect; // CREATES THE IMAGE'S SPECS
s_rect.x = 100; // just like the window, the x and y values determine it's displacement from the origin which is the top left of your window
s_rect.y = 100;
s_rect.w = 640; //width of the texture
s_rect.h = 480; // height of the texture

time = SDL_GetTicks(); //Gets the current time

while (time + 2000 < SDL_GetTicks()) //adds 2 seconds to the past time you got and waits for the present time to surpass that
{
SDL_RenderClear(r);
SDL_RenderCopy(r, s, NULL, &s_rect); // THE NULL IS THE AREA YOU COULD USE TO CROP THE IMAGE
SDL_RenderPresent(r);

}

SDL_DestroyTexture(s);
SDL_DestroyRenderer(r);
SDL_DestroyWindow(w);

return 0; //returns 0, closes the program.
}

如果你想在窗口上看到一个关闭按钮并希望它生效然后创建一个事件然后将它添加到while区域以检查它是否等于SDL_Quit();,我没有包括它因为你希望它在 2 秒内立即关闭,从而使关闭按钮无用。

快乐编码:D

关于c++ - SDL2不使用纹理绘制图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22627779/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com