简体   繁体   English

SDL_image无法使用IMG_LoadTexture()加载.png文件

[英]SDL_image Can't load .png file with IMG_LoadTexture()

While trying to load a .png file with IMG_LoadTexture(renderer, "idle.png") SDL_GetError() says: "Couldn't open idle.png" There are no compiler errors, just a black window appears. 尝试使用IMG_LoadTexture(renderer,“ idle.png”)加载.png文件时,SDL_GetError()表示:“无法打开idle.png”没有编译器错误,仅出现一个黑色窗口。

This is my main.cpp 这是我的main.cpp

#include <stdlib.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <iostream>

int main(int argc,  char** argv) {
    SDL_Event event;
    SDL_Renderer *renderer = NULL;
    SDL_Texture *texture = NULL;
    SDL_Window *window = NULL;

    SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO);
    SDL_CreateWindowAndRenderer(
            800, 600,
            0, &window, &renderer
    );
    IMG_Init(IMG_INIT_PNG);
    texture = IMG_LoadTexture(renderer, "idle.png");
    std::cout << SDL_GetError();

    while (1) {
        SDL_RenderCopy(renderer, texture, NULL, NULL);
        SDL_RenderPresent(renderer);
        if (SDL_PollEvent(&event) && event.type == SDL_QUIT)
            break;
    }
    SDL_DestroyTexture(texture);
    IMG_Quit();
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return EXIT_SUCCESS;
}

But I guess the problem is the way I link the library. 但是我想问题是我链接库的方式。 I installed sdl2, sdl2_image and libpng. 我安装了sdl2,sdl2_image和libpng。

CMakeLists.txt: 的CMakeLists.txt:

cmake_minimum_required(VERSION 3.12)
project(untitled)

set(CMAKE_CXX_STANDARD 17)

add_executable(untitled main.cpp)

INCLUDE(FindPkgConfig)

PKG_SEARCH_MODULE(SDL2 REQUIRED sdl2)
PKG_SEARCH_MODULE(SDL2IMAGE REQUIRED SDL2_image>=2.0.0)

INCLUDE_DIRECTORIES(${SDL2_INCLUDE_DIRS} ${SDL2IMAGE_INCLUDE_DIRS})
TARGET_LINK_LIBRARIES(untitled ${SDL2_LIBRARIES} ${SDL2IMAGE_LIBRARIES})

You are loading the image from the current working directory (CWD) of your application. 您正在从应用程序的当前工作目录(CWD)加载映像。 That is not necessarily the same directory as your executable is in (it depends on how it is launched), which you seem to assume. 这似乎不一定与您的可执行文件所在的目录相同(取决于它的启动方式)。

3 easy ways to fix: 3种简单的修复方法:

  1. change the cwd at runtime to where the file is and load as you do now. 在运行时将cwd更改为文件所在的位置,然后像现在一样加载。
  2. provide an absolute path to the file when loading, so cwd is irrelevant. 加载时提供文件的绝对路径,因此cwd无关紧要。
  3. obtain the path to the executable at runtime and then construct a path to the file relative to where the executable is. 在运行时获取可执行文件的路径,然后构造相对于可执行文件所在位置的文件路径。 (best option in my opinion since it's robust against moving your project around/installing to a different location). (我认为这是最好的选择,因为它在将您的项目移至其他位置/将其安装到其他位置方面非常可靠)。

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

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