It often seems that I'm drawn to questions on Stack Overflow that have to do with manipulating pixels directly. This week, I fielded a question from someone who wasn't happy with the solution he was using where he was using the graphics object and filling it with the bitmap he was trying to scroll.
I gave him syntax to do it with copyPixels, but what I gave him didn't completely solve his problem, since copyPixels doesn't automatically create multiple copies of the bitmap to fill in the area left empty when you move the graphic. I came up with some code that worked, but it wasn't optimal, and I didn't give a good explanation of why it worked.
So I thought I'd share a better solution with everyone, along with an explanation of what's happening.
Anatomy of an Endlessly Scrolling Background
Let's take the example of a background scrolling from right to left. To create a scrolling background, you need to break the image into two segments—one on the left and one on the right. The pixels on the left side of the image need to slide in from the right hand side, replacing the pixels that are sliding off. In fact, they are the very same pixels that slid off.
This means that the rectangle we're using for the source of these pixels (again, on the left side of the image), is continually growing as it is joined by more and more pixels. By the same token, the pixels on the right hand side, which are the ones that are still left after the pixels moved around to slide in from the right, occupy a rectangle that is constantly shrinking.
To complete the effect, we transpose the two rectangles so that the shrinking right-hand rectangle is on the left side and the growing rectangle from the left side of the image is on the right. Check out this demo, where the red and blue rectangles show where the source pixels are coming from and the lower animation shows the finished effect.
About the Bathroom Still Life
Sometimes I walk into the bathroom and I see something like this, so I'll go get my phone and snap a picture. It's almost as if my toiletries have lives of their own. By capturing these moments, I can share that secret life in some way. I think of this one as "Toothbrush 'From here to Eternity.'"