SDL2加载嵌入式二进制

时间:2019-05-19 12:49:24

标签: c sdl-2

嗨,我正在尝试使用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;


}

1 个答案:

答案 0 :(得分:0)

在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
}

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

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
}