我试图使用带有c ++的sdl在屏幕上获取一个矩形。文件编译但它停止工作并返回255.你能推荐一些更好的东西吗?
这是代码:
SDL_Window* window;
SDL_Rect* SrcR; //rectangle
SDL_Rect* DestR; //dist rectangle
SrcR->x = 0;
SrcR->y = 0;
SrcR->w = SHAPE_SIZE;
SrcR->h = SHAPE_SIZE;
DestR->x = 100 / 2 - SHAPE_SIZE / 2;
DestR->y = 50 / 2 - SHAPE_SIZE / 2;
DestR->w = SHAPE_SIZE;
DestR->h = SHAPE_SIZE;
SDL_Init(SDL_INIT_VIDEO);
window = SDL_CreateWindow("title", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 200, 250, NULL);
SDL_Renderer *renderer = NULL;
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
SDL_Texture *texture = NULL;
SDL_Surface* surface;
surface = SDL_GetWindowSurface(window);
SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 0, 0));
texture = SDL_CreateTextureFromSurface(renderer, surface);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, SrcR, DestR); //here i got error before
SDL_RenderPresent(renderer);
答案 0 :(得分:1)
您错误地使用了SDL_Rect
。你已经为它定义了一个指针(见下文),但你永远不会为它分配内存。然后,您尝试将值分配给您也未能初始化的rects,因此可能有任何旧的垃圾地址。
SDL_Rect* SrcR; //rectangle
SDL_Rect* DestR; //dist rectangle
SrcR->x = 0;
SrcR->y = 0;
SrcR->w = SHAPE_SIZE;
SrcR->h = SHAPE_SIZE;
DestR->x = 100 / 2 - SHAPE_SIZE / 2;
DestR->y = 50 / 2 - SHAPE_SIZE / 2;
DestR->w = SHAPE_SIZE;
DestR->h = SHAPE_SIZE;
应如下:
SDL_Rect SrcR; //rectangle
SDL_Rect DestR; //dist rectangle
SrcR.x = 0;
SrcR.y = 0;
SrcR.w = SHAPE_SIZE;
SrcR.h = SHAPE_SIZE;
DestR.x = 100 / 2 - SHAPE_SIZE / 2;
DestR.y = 50 / 2 - SHAPE_SIZE / 2;
DestR.w = SHAPE_SIZE;
DestR.h = SHAPE_SIZE;
或者您可以按如下方式直接初始化它们:
SDL_Rect SrcR = {0, 0, SHAPE_SIZE, SHAPE_SIZE};
SDL_Rect DestR = {(50 - SHAPE_SIZE/2), (25 - SHAPE_SIZE/2), SHAPE_SIZE, SHAPE_SIZE};
最后,在调用SDL_RenderCopy
时,请记住您现在正在使用实例而不是指针,因此您需要传递rects的地址:
SDL_RenderCopy(renderer, texture, &SrcR, &DestR);
你肯定应该在注释中提到的SDL_ *函数上进行一些错误检查,特别是在你从函数中获取指针的时候。