Scrolling an Image in C#

On occasion I have seen people asking about making scrolling images. Often times they are asking this question in response to creating their own games to get something like a scrolling background without needing to use a picturebox… which can be pretty bulky. One way to do this is by taking the reigns and controlling the paint event of a control or form. By determining what is drawn and when, you can easily making scrolling images. We will give you a taste of this in C# right here on the Programming Underground!

The paint event.. an event that fires when the control, or in this case form, needs to update its appearance. It needs to update its appearance whenever its display needs to be redrawn. Like when the form is covered up by another window and then uncovered, when it is resized, or simply when the controls on the form need to show new information. Most controls have a paint event in addition to the form itself having one. Each paint event is responsible for updating the controls itself.

In our example below we load in a jpg picture from disk. We get some information about it, like its width and height, and then paint it onto the form at a specified location. We do this painting through the use of a Graphics object. If you are not familiar with the Graphics object, think of it like a canvas. In order to show a picture to your prospective buyers at the DIC art gallery, you need to paint on something. You would paint on a form using this graphics object like you would paint a picture using a canvas. If you would like to know more about this object, plus the load of things it can do, I suggest you do a simple search on MSDN for “Graphics Object” and read up. It has a lot of great and useful methods for drawing lines, images, shapes, colors, patterns etc.

The second thing we use is the keypressed event to determine the type of keys that are being pressed on the keyboard. We are looking for our directional arrow keys to manipulate where in our source image to copy from. When we hit the right key, we increment the imagex value by 2 and thus draw from our source image starting at coordinates 2, 0. When we hit down, we start drawing from our source at the coordinates 2, 2 and so on.

The result is that we can scroll through the image with a nice smooth fluid motion. Almost like a miniature window showing only a piece of a bigger picture. As you will notice, if we hold the right key it will pan across the image just like you might have seen in the background of a Super Mario 1, 2, or 3 game back in the gold old days of Nintendo.

Of course the panning will stop when the image reaches the sides. In a game situation you may actually have this point of the animation wrap back around to the beginning to create a repeating scrolling effect. You may choose to put in a new image which transitions from one design to another. The choice is up to you and your game design.

You can put this code directly into a C# windows application (2008 Express preferable) and give it a whirl. Just remember to replace the actual image name from Midnight_dragon.jpg to the image of choice. Leave the window at 300,300 and make the image much bigger (something like 1024 x 768 wallpaper should suffice).

namespace scrollimage
	public partial class Form1 : Form
		public Form1()

		// Source image start point
		private int imagex = 0;
		private int imagey = 0;

		// Dimensions of picture being drawn
		private int imagewidth = 0;
		private int imageheight = 0;

		// Reference to the image being drawn
		private Image image;

		private void Form1_Load(object sender, EventArgs e)
			// Load the image from disk and get its dimensions
			image = Image.FromFile("c:\\Midnight_Dragon.jpg");
			imagewidth = image.Width;
			imageheight = image.Height;

			// This sets up a double buffer for our form. 
			// Double buffering allows an image to be drawn off screen and then drawn
			// directly to the graphics object of our form with no flickering.
			this.SetStyle(ControlStyles.DoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);

		private void Form1_Paint(object sender, PaintEventArgs e)
			// Draw the image starting at 0,0 of the form with the forms width and height
			// We draw it using the source image starting at imagex, imagey and making it the form width and height
			e.Graphics.DrawImage(image, new Rectangle(0, 0, this.Width, this.Height), new Rectangle(imagex, imagey, this.Width, this.Height), GraphicsUnit.Pixel);

		// This event simply detects when keys are pressed down, checks if they are arrow keys
		// and then updates the imagex and imagey variables (remember these determine where in the source image to pull from)
		private void Form1_KeyDown(object sender, KeyEventArgs e)
			if (e.KeyCode == Keys.Right)
				imagex += 2;
				if (imagex >= (imagewidth - this.Width)) { imagex = imagewidth - this.Width; }
			else if (e.KeyCode == Keys.Left)
				imagex -= 2;
				if (imagex <= 0) { imagex = 0; }

			if (e.KeyCode == Keys.Down)
				imagey += 2;
				if (imagey >= (imageheight - this.Height)) { imagey = imageheight - this.Height; }
			else if (e.KeyCode == Keys.Up)
				imagey -= 2;
				if (imagey <= 0) { imagey = 0; }

			// Lastly, invalidate the form so that it activates its paint event.

If you step through the code and read the comments you will see that we are simply modifying where in the source image we copy from and placing it on the form. It is very basic and a great setup for creating the initial background of a little 2D windows game in C#. Place your other images on top of it (paint them on to) and you suddenly have Mario running across the background.

Feel free to take what you like of this code and modify it free without penalty. As with all source code here on the Programming Underground it is in the public domain “as is” and open to modifications. After all, that is what The Coders Lexicon is all about, sharing the code love. Enjoy and thanks for reading! 🙂

About The Author

Martyr2 is the founder of the Coders Lexicon and author of the new ebooks "The Programmers Idea Book" and "Diagnosing the Problem" . He has been a programmer for over 25 years. He works for a hot application development company in Vancouver Canada which service some of the biggest tech companies in the world. He has won numerous awards for his mentoring in software development and contributes regularly to several communities around the web. He is an expert in numerous languages including .NET, PHP, C/C++, Java and more.