#Loading and displaying images

1 messages · Page 1 of 1 (latest)

eternal ibex
#

I've been messing around trying to load and display pngs, but nothing i've done yet seems to work. Does anyone have any nice examples of that sort of code? the only example i could find is the widgetpedia example and that doesn't involve image reading/decoding.

remote basin
#

The "Basic Widgets" part of the demo renders a png file, the zig favicon. See src/Examples/basic_widgets.zig and search for this line:
const image_source: dvui.ImageSource = .{ .imageFile = .{ .bytes = zig_favicon, .name = "zig favicon" } };

#

The general strategy is to load the bytes of the image file (or use @embedFile) and pass those bytes to ImageSource and render it with dvui.image(). The image is automatically decoded to a texture and cached.

#

Does that help?

eternal ibex
#

Thank you so much! Can't believe I missed that, I'll make sure to look more closely next time.

remote basin
#

No problem at all, let me know if there is a place you looked where we could add doc comments or anything to help the next person in your situation!

potent merlin
#

If you are dynamically fetching images in an app i would highly recommend making a texture and keeping just the texture alive.

This snippet can come in handy for you or anyone else who comes across this post

if (dvui.textureGetCached(url_key)) |texture| {
  return .{ .texture = texture };
}

const source: dvui.ImageSource = .{ .imageFile = .{ .bytes = res.body } };
const texture = try dvui.Texture.fromImageSource(source);
dvui.textureAddToCache(url_key, texture);
if (auto_retain) dvui.textureRetain(url_key, url_id);
return .{ .texture = texture };
eternal ibex
remote basin
uneven ravine
remote basin
uneven ravine
#

Yeah, that makes sense. So if I have a main screen and I keep using it, it will be in the cache.
But if I have tabs or something and want to be able to switch back quickly, then I would retain it?

remote basin
#

There are two strategies:

  1. collect the hashes as you textureRetain them, and then textureRelease at some point
#

(That's the manual method)

#
  1. use textureRetainToken, and then at some point call retainClear
#

The demo uses method 2 to tie the texture lifetime to a widget lifetime (the demo floatingWindow widget).

#

Search for "retain_token" in src/Examples.zig for details

uneven ravine
#

Thanks for the clarification. I'm avoiding this problem right now, but want to be aware when I look into tabs.

potent merlin
uneven ravine
#

So if it scrolls off the screen, that can also invalidate it? In my case, (toy web browser) I fetch it from the network, create the texture, free the bytes. I guess I would also need to retain it until that page is unloaded.

potent merlin
#

yes, that would be my recommendation, as if it gets invalidated that means u would need to refetch the image (or keep the bytes around)

uneven ravine
#

Thank you for your help.