linebender / druid

A data-first Rust-native UI design toolkit.
https://linebender.org/druid/
Apache License 2.0
9.52k stars 569 forks source link

How to cache TextLayout and Image in a custom widget #2077

Open chrisspre opened 2 years ago

chrisspre commented 2 years ago

Creating a custom widget with a quite a few Images and some TextLayouts.

I was able to create TextLayout/Image in Widget's update method , safe it in the Widget (as an Option<>) and then use it in the paint method. This seems like a hack and has the problem that the update method needs to be called once for it to work.

Is there a preferred way to cache the TextLayout/Image and avoid the overhead of creation in every paint?

maan2003 commented 2 years ago

You need to create the Image/TextLayout on LifeCycle::WidgetAdded and then update it when needed in update()

chrisspre commented 2 years ago

Thanks. I will give that a try.

Is the "pattern" to store it via a Option on the widget's struct the right approach? Is there ways to avoid the Option, or a better place to cache?

maan2003 commented 2 years ago

we also use Option in struct: https://github.com/linebender/druid/blob/2d80ca04312746567219ebed2aacc0ee5d72b6c7/druid/src/widget/image.rs#L72-L78

chrisspre commented 2 years ago

LifeCycleCtx does not implement RenderCtx and therefore does not have a make_image method.

longmathemagician commented 2 years ago

LifeCycleCtx does not implement RenderCtx and therefore does not have a make_image method.

Did you ever happen to find a solution to this?

maan2003 commented 2 years ago

Just store an Option<PietImage> and populate it on first paint