Immediate-Mode-UI / Nuklear

A single-header ANSI C immediate mode cross-platform GUI library
https://immediate-mode-ui.github.io/Nuklear/doc/index.html
Other
9.17k stars 553 forks source link

Creating a nk_image with the sdl_renderer backend #599

Closed zoogies closed 7 months ago

zoogies commented 9 months ago

First, I would like to express my appreciation for Nuklear and its support of the sdl_renderer as a backend.

My question is pretty simple: how can I create an nk_image from a file (or from a SDL_Texture or SDL_Surface) using the sdl_renderer backend?

There are no such examples included in the repo (for this backend) and I've repeatedly come back every few weeks to this topic and tried persistently to no avail. Reading Nuklear and SDL source has not helped me figure this out, but I am more than willing to investigate any resources anyone is willing to throw my way! :)

RobLoach commented 8 months ago

nk_image is...

struct nk_image {nk_handle handle; nk_ushort w, h; nk_ushort region[4];};

handle.ptr should point to an SDL_Texture/SDL_Surface, and you'd interact with it from there.

zoogies commented 7 months ago

It seems that my issue was attempting to pass nk_image_ptr an SDL_Surface, or the (void*) pixels field of the Surface, rather than a SDL_Texture * which does indeed work.

Here is a small snippet using SDL and SDL_Image to display an nk_image inside of a button (for anyone who stumbles upon this issue in the future.

// do this once, sometime at init:
SDL_Surface *icon_build_surface = IMG_Load(PATH_TO_YOUR_IMAGE_HERE);
SDL_Texture *icon_build_tex = SDL_CreateTextureFromSurface(POINTER_TO_YOUR_SDL_RENDERER, icon_build_surface);
icon_build_texture = nk_image_ptr(icon_build_tex);
SDL_FreeSurface(icon_build_surface);

// usage of the image during nuklear lifecycle:
nk_button_image_label(ctx, icon_build_texture, "Build", NK_TEXT_CENTERED);

// of course, free your texture before shutting down:
SDL_DestroyTexture(icon_build_tex);

Screenshot_20240221_140225

The surfaces probably don't work due to variable SDL_PixelFormat's, but I am not familiar enough with the implementation to know if that's truly the case.

Additionally, I've gone ahead and opened a PR to add an example of nk_button_image_label to the sdl_renderer backend. Hopefully that will be a good resource in the future to illustrate this.

Immediate-Mode-UI/Nuklear#613