【问题标题】:SDL2 How can I render pixels from raw format?SDL2 如何从原始格式渲染像素?
【发布时间】:2018-11-20 14:32:59
【问题描述】:

我正在尝试渲染自定义图像,它要求我将文件加载到内存中并通过 SDL 将其渲染出来。图像是原始格式,我想如果我可以渲染

我的代码可能是垃圾,所以我愿意接受更改。

void Create_SDL_Window()
{

        SDL_Init(SDL_INIT_EVERYTHING);
        IMG_Init(IMG_INIT_PNG);
        window = SDL_CreateWindow("Test Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
        renderer = SDL_CreateRenderer(window, -1, 0);
        printf("Window And Renderer Created!\n");
}






int main(){
FILE* customImage = fopen(Path, "rb");



Create_SDL_Window();

while (!quit){

        void *p;
        p = customImage;

        SDL_Texture* buffer = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_BGRA8888,SDL_TEXTUREACCESS_STREAMING, 800, 600);

        SDL_LockTexture(buffer, NULL, &p, &pitch);

        SDL_UnlockTexture(buffer);
        SDL_RenderCopy(renderer, buffer, NULL, NULL);


        SDL_RenderPresent(renderer);



while (SDL_PollEvent(&e)){
        //If user closes the window
        if (e.type == SDL_QUIT){
                quit = true;
        }
        //If user presses any key
        if (e.type == SDL_KEYDOWN){
        //      quit = true;
        }
        //If user clicks the mouse
        if (e.type == SDL_MOUSEBUTTONDOWN){
        ///     quit = true;
                }
        }

        SDL_RenderPresent(renderer);

}

【问题讨论】:

    标签: c byte sdl render pixel


    【解决方案1】:

    你的事情倒退了。您应该注意到SDL_LockTexture 采用指向指针的指针。这是因为 SDL 已经有一个适合纹理大小的缓冲区,它需要告诉您地址(和间距),以便您可以写入此缓冲区。

    您还有一个问题,您认为可以使用FILE* 作为像素缓冲区。这根本不是真的。 FILE* 是一个指向描述文件结构的指针,而不是它的内容。

    你需要做的是这样的:

    // create your empty texture
    ...
    int pitch = 0;
    char* p = NULL;
    SDL_LockTexture(buffer, NULL, &p, &pitch);
    ... // Error checking
    
    // now open your file and mmap it
    int fd = open(Path, O_RDONLY);
    struct stat sb;
    fstat(fd, &sb);
    
    const char* memblock = mmap(NULL, sb.st_size, PROT_READ, MAP_SHARED, fd, 0);
    ... // Error checking
    
    // now you need to copy the data from the file to the pixel buffer
    // you claim you are working with 800x600 32bit image data
    
    for (int y = 0; y < 600; ++y)
    {
        const char* src = &memblock[y * pitch]; // is this really the pitch of the file? you didn't specify....
        char* dst = &p[y * pitch];
        memcpy(dst, src, 800*4); // width * size of a pixel
    }
    

    此代码假定您没有在其他地方犯错,例如纹理大小或像素格式。您还会注意到代码中存在一些您需要找出的未知数。

    您也可以尝试SDL_UpdateTexture,它将接受指向像素的指针,就像您在代码中尝试的那样。但是,它可能比SDL_LockTexture 慢得多,并且您仍然需要实际读取文件(或者更好的是mmap 它)才能获取要传入的像素。

    如果SDL_Image 知道如何读取您的“RAW”文件,第三种选择是使用IMG_Load 获取图像的SDL_Surface,然后使用SDL_CreateTextureFromSurface 从该表面创建纹理

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-12
      • 2012-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多