【问题标题】:How to display a image on a user defined rectangle with SDL_surface?如何使用 SDL_surface 在用户定义的矩形上显示图像?
【发布时间】:2017-04-07 01:52:33
【问题描述】:

我正在和我的朋友一起做一个项目,我们在 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);
}

//这是在实际的draw函数中。

display_surface = SDL_GetWindowSurface( display_window ); 
if(display_surface == NULL ) 
{
    printf(" null im exiting here %s\n", 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);

谢谢各位! 如果您需要更多信息,请告诉我,这是我第一次发帖,我试图把我能想到的所有信息都放上来。

【问题讨论】:

    标签: c++ sdl-2


    【解决方案1】:

    使用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

    【讨论】:

      猜你喜欢
      • 2014-04-29
      • 2020-12-14
      • 1970-01-01
      • 2016-10-28
      • 1970-01-01
      • 2014-07-06
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多