如何使用SDL_surface在用户定义的矩形上显示图像?

How to display a image on a user defined rectangle with SDL_surface?

本文关键字:显示 显示图 图像 定义 SDL 何使用 surface 用户      更新时间:2023-10-16

我和我的朋友一起做一个项目,我们在 SDL 中遇到了表面和窗口的问题。

目前,我们能够创建一个窗口并在该窗口上显示一个矩形并移动它。我们要做的下一件事是拍摄图像并将其显示在矩形上,然后在屏幕上移动它。

我们从获取SDL_window*并将其转换为SDL_surface*开始,尽管这会获取图像并将其显示在窗口的背景上。

有没有办法将我们创建的矩形变成表面并在该矩形上显示图像?

我也尝试过使用纹理,当我尝试移动它时它会扭曲图像,并且整个图像不会随矩形一起移动。

这发生在构造函数中

temp_image_sur = IMG_Load( image_location.c_str() );
if( temp_image_sur == NULL )
{
std::cout << "Image could not be loaded" <<std::endl;
exit(1);
}

这是在实际的绘制函数中。

display_surface = SDL_GetWindowSurface( display_window ); 
if(display_surface == NULL ) 
{
printf(" null im exiting here %sn", SDL_GetError());
exit(1);
}
image_surface = SDL_ConvertSurface( temp_image_sur, display_surface->format, 0 );
image_size = { this->location.x, this->location.y, this->size.width, this->size.height };
SDL_BlitSurface( image_surface, &image_size, display_surface, &image_size );

这是我们第一次尝试时所做的,图像显示在基本窗口中。我相信我理解为什么它显示在基本窗口上,这是因为我们使用该窗口作为表面,尽管我很困惑如何使用户定义的矩形成为表面?

我们确实尝试使用SDL_CreateRGBSurface,尽管当我们这样做时,屏幕上也没有显示任何内容。

display_surface = SDL_CreateRGBSurface(0, this->size.width, this->size.height, 1, this->color.red, this->color.green, this->color.blue, this->color.alpha);

谢谢大家! 如果您需要更多信息,请告诉我,这是我第一次发布,我试图把我能想到的所有信息都放进去。

使用SDL_CreateTextureFromSurface从图像表面创建纹理:

SDL_Texture* image_surface = SDL_CreateTextureFromSurface(renderer, temp_image_sur);

(记得用SDL_DestroyTexture释放它)

然后使用SDL_RenderCopy绘制它:

SDL_RenderCopy(renderer, image_texture, nullptr, &image_rect);

其中image_rectSDL_Rect和要将图像绘制到的目标矩形,例如:

SDL_rect image_rect = {10, 10, 200, 200};

要移动图像,只需更改image_rect.x和/或image_rect.y