@@ -141,6 +141,34 @@ public final class Image extends Resource implements Drawable {
141141
142142 private List <Consumer <Image >> onDisposeListeners ;
143143
144+ private record CachedHandle (ImageHandle handleContainer , int requestedWidth , int requestedHeight ) {
145+
146+ public void destroy () {
147+ if (handleContainer != null ) {
148+ handleContainer .destroy ();
149+ }
150+ }
151+
152+ public boolean isReusable (int height , int width ) {
153+ if (handleContainer == null ) {
154+ return false ;
155+ }
156+ return (requestedHeight == height && requestedWidth == width )
157+ || (handleContainer .height == height && handleContainer .width == width );
158+
159+ }
160+
161+ public long getHandle () {
162+ if (handleContainer != null ) {
163+ return handleContainer .handle ;
164+ }
165+ return -1 ;
166+ }
167+ };
168+
169+ // Initialize lastRequestedHandle with -1 for size-related fields to indicate uninitialized values
170+ CachedHandle lastRequestedHandle = new CachedHandle (null , -1 , -1 );
171+
144172private Image (Device device , int type , long handle , int nativeZoom ) {
145173 super (device );
146174 this .type = type ;
@@ -826,19 +854,15 @@ interface HandleAtSizeConsumer {
826854}
827855
828856void executeOnImageHandleAtSize (HandleAtSizeConsumer handleAtSizeConsumer , int widthHint , int heightHint ) {
829- ImageData imageData ;
830- imageData = this .imageProvider .loadImageDataAtSize (widthHint , heightHint );
831- executeOnImageHandle (handleAtSizeConsumer , imageData );
832- }
833-
834- private void executeOnImageHandle (HandleAtSizeConsumer handleAtSizeConsumer , ImageData imageData ) {
835- ImageHandle handleContainer = init (imageData , -1 );
836- long tempHandle = handleContainer .handle ;
837- try {
838- handleAtSizeConsumer .accept (tempHandle , new Point (imageData .width , imageData .height ));
839- } finally {
840- handleContainer .destroy ();
857+ if (!lastRequestedHandle .isReusable (heightHint , widthHint )) {
858+ ImageData imageData ;
859+ imageData = this .imageProvider .loadImageDataAtSize (widthHint , heightHint );
860+ lastRequestedHandle .destroy ();
861+ ImageHandle handleContainer = init (imageData , -1 );
862+ lastRequestedHandle = new CachedHandle (handleContainer , widthHint , heightHint );
841863 }
864+ handleAtSizeConsumer .accept (lastRequestedHandle .getHandle (),
865+ new Point (lastRequestedHandle .handleContainer ().width , lastRequestedHandle .handleContainer ().height ));
842866}
843867
844868/**
@@ -1073,6 +1097,7 @@ void destroy () {
10731097
10741098private void destroyHandles () {
10751099 destroyHandles (__ -> true );
1100+ lastRequestedHandle .destroy ();
10761101}
10771102
10781103@ Override
0 commit comments