繁体   English   中英

SDL从文件加载图像

[英]SDL load image from file

我正在尝试学习SDL 2.0,并且一直在关注lazyfoo教程。 问题在于这些教程将所有内容保存在一个文件中。 因此,当我开始一个新的游戏项目时,我试图分解一些东西。 我的问题是,当我将纹理类与其余的类分开时,有时会导致程序崩溃,但并非总是崩溃,但经常崩溃。

我在课堂上使用一个全局窗口和一个全局渲染器。 我在程序中的不同位置遇到段错误,但总是在以下功能之一中发生。

bool myTexture::loadFromFile(string path) {
  printf("In loadFromFile\n");

  //Free preexisting texture
  free();
  //The final texture
  SDL_Texture *l_newTexture = NULL;

  //Load image at specified path
  SDL_Surface *l_loadedSurface = IMG_Load(path.c_str());
  if(l_loadedSurface == NULL) {
    printf("Unable to load image %s! SDL_image Error: %s\n", path.c_str(),      IMG_GetError());
  } else {
    //Color key image for transparancy
    //SDL_SetColorKey(l_loadedSurface, SDL_TRUE, SDL_MapRGB(l_loadedSurface->format, 0,  0xFF, 0xFF));
    //Create texture from surface pixels
    l_newTexture = SDL_CreateTextureFromSurface(g_renderer, l_loadedSurface);

    if(l_newTexture == NULL) {
      printf("Unable to create texture from %s! SDL Error: %s\n", path.c_str(),   SDL_GetError());
    } else {
      //Get image dimensions
      m_width = l_loadedSurface->w;
      m_height = l_loadedSurface->h;
    }
    //Get rid of old loaded surface
    SDL_FreeSurface(l_loadedSurface);
  }
  m_texture = l_newTexture;
  //return success
  printf("end from file \n");

  return m_texture != NULL;
}

void myTexture::free() {
  printf("In myTexture::free\n");
  //Free texture if it exist
  if(m_texture != NULL) {
    cout << (m_texture != NULL) << endl;
    SDL_DestroyTexture(m_texture);
    printf("Destroyed m_texture\n");
    m_texture = NULL;
    m_width   = 0;
    m_height  = 0;
  }
  printf("end free\n");
}

在阅读了SDL和其他内容之后,我了解到可能有一些线程试图取消分配不允许它取消分配的内容。 但是我还没有任何线程。

我设法自己解决了这个问题。 事实证明,我从未创建过一个真正愚蠢的新myTexture对象。 但是我仍然不明白它有时是如何渲染的……对我而言,这根本没有任何意义。 我从未创建过它,但有时仍可以调用它的render函数...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM