Solved: replacing an image (from newImage) with a new image

Back in 2010-2013, a number of people asked about replacing an image created via display.newImage with a new image.  With one exception I found, a hint that eventually led me to a nice technique, most answers were variations of "destroy the existing image and create a new one.  The one hint pointed to a post about “Graphics 2.0”, but the link was dead.  The Way Back Engine helped, and I eventually found what I needed.

I now have the following code, which works.  Note: in my case, both pictures have the same resolution.

Note: the “fill”'d pictures seem to display at the same size as the original display.newImage picture.

I have a function, bh_swap, which replaces the image in img_tahoe every time it’s invoked, alternating between two images (in filename1 and dir1, and filename2 and dir2):

swap\_next\_num = 1 -- alternates between 1 and 2 function swap\_pic () -- swap the picture img\_tahoe has with filename1, filename2, filename1... local dir, f, new\_fill\_info if (event.phase == "ended") then if swap\_next\_num == 1 then f = filename1 dir = dir1 swap\_next\_num = 2 else f = filename2 dir = dir2 swap\_next\_num = 1 end new\_fill\_info = { type = "image", filename = f, baseDir = dir} -- print ("Fill with " .. new\_fill\_info.filename) img\_tahoe.fill = new\_fill\_info -- change picture! -- I know this photo is centered on the screen ... -- let's randomly reposition it by a small amount, to -- minimize possible screen burn-in. A few pixels whenever -- the picture changes isn't noticeable. xoff = get\_rand\_int (5) - 2 yoff = get\_rand\_int (5) - 2 img\_tahoe.x = centerX + xoff img\_tahoe.y = centerY + yoff end end -- swap\_pic proc -------------------------- -- at some point, I did the following earlier to create the initial picture... new\_img = display.newImage (filename, dir, centerX, centerY)

I then call swap_pic periodically (in my case, once every 20 to 30 seconds).

Hope that’s of interest to someone.

Stan

P.s.: sorry, the forum software highlights “reserved” words in Lua comments … because one can’t choose “Lua” as one of the languages, so I chose “generic”

This is covered in the image swapping tutorial:  https://docs.coronalabs.com/tutorial/media/swapImages/index.html#fill-swap

Rob

Interesting, thanks Rob!

It’s a topic that ought to be on the display.newImage documentation page, I think … even one or two sentences would suffice.

(And, thanks to my post, it’s visible to people who search the forums :slight_smile:

thanks,

Stan

This is covered in the image swapping tutorial:  https://docs.coronalabs.com/tutorial/media/swapImages/index.html#fill-swap

Rob

Interesting, thanks Rob!

It’s a topic that ought to be on the display.newImage documentation page, I think … even one or two sentences would suffice.

(And, thanks to my post, it’s visible to people who search the forums :slight_smile:

thanks,

Stan