【问题标题】:SDL2 Load embedded binarySDL2 加载嵌入式二进制文件
【发布时间】:2019-10-06 01:25:01
【问题描述】:

您好,我正在尝试使用 SDL2 加载嵌入的 png。我之前只设法创建了文件,但没有直接加载它。我试着把 _binary_flower_png_ 在 IMG_LoadTexture 中,但它没有工作。这是我走了多远(它工作正常,但我不会创建文件)

 #include <stdlib.h>

#include <stdio.h>

#include <SDL2/SDL.h>

#include <SDL2/SDL_image.h>

extern const char _binary_flower_png_start[];

extern const char _binary_flower_png_end[];

extern const int _binary_flower_png_size;

int main()
{

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(
        500, 500,
        0, &window, &renderer
    );

    //File create

FILE *f = fopen("flower.png", "wb");
    fwrite(_binary_flower_png_start, &_binary_flower_png_end, 
    &_binary_flower_png_start, f);
    fclose(f);
    printf("File created");

    //Load here

    IMG_Init(IMG_INIT_PNG);
    texture = IMG_LoadTexture(renderer, "flower.png");

//Render

    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;


}

【问题讨论】:

  • 您需要IMG_LoadTexture_RWSDL_RWFromConstMem

标签: c sdl-2


【解决方案1】:

在 SDL 2.0 中加载任何资源(无论是来自 SDL_image、SDL_mixer、SDL_ttf 等)的方式是使用指向该内存的 SDL_RWops 指针。

从内存缓冲区加载 .png 文件:

extern uint8_t *buffer; // presumably, this holds the bytes of a .png file  
extern int cbBuffer; // the size of the .png data buffer

SDL_Surface *loadPng(void) {
  SDL_Surface *result = NULL;
  SDL_RWops *stream = SDL_RWFromConstMem(buffer, cbBuffer);
  if (stream == NULL) {
    // error handling for failure - call SDL_GetError()
  }
  else {
    result = IMG_LoadPNG_RW(stream); // does not free the source stream
    SDL_RWclose(stream);
  }
  return result; // may be NULL - caller should check
}

或者,您可以使用 SDL_RWFromFile() 函数来加载 .png 文件,如果它尚未加载到外部缓冲区中:

SDL_Surface *loadPng(const char *path) {
  SDL_Surface *result = NULL;
  SDL_RWops *stream = SDL_RWFromFile(path, "rb");
  if (stream == NULL) {
    // error handling for failure - call SDL_GetError()
  }
  else {
    result = IMG_LoadPNG_RW(stream); // does not free the source stream
    SDL_RWclose(stream);
  }
  return result; // may be NULL - caller should check
}

【讨论】:

    猜你喜欢
    • 2019-04-19
    • 2015-03-11
    • 1970-01-01
    • 1970-01-01
    • 2017-09-21
    • 2014-10-17
    • 2012-12-19
    • 2016-12-01
    • 1970-01-01
    相关资源
    最近更新 更多