Endless Scrolling Bathroom

english mobile

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.

Download the source code.

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.'"


Unknown said...

Pretty neat, but may I suggest using BitmapFill on a Shape instead? Bitmapfill has the benefit of working even if the background is larger than your source image, and can scroll by less than one pixel at a time, which creates a smoother effect. Its also computationally simpler if you want to scroll on two axes.
Check out the source code here:

Amy B said...

Great suggestion for visitors to the site to check out if they weren't aware of it. However, if you go to the link with the original question, the person asking wasn't satisfied with the method you suggest, because it didn't perform well. I thought I mentioned this in my post, but it's possible I wasn't clear enough.