C# Tutorial – Move a transparent image using Paint Event in Windows Form and Visual Studio

Hi, welcome to part 3 of the working with transparent images series with MOO ICT. In this tutorial we will cover how to make an object bounce around the form using paint event and timer. We want to make cool looking apps and games using windows form and we cannot get the results we want while using picture boxes and the labels. So we have drove right into the deep end of programming using the paint event and the timer to invoke the paint event when we want to. This will be very simply application to make and it will help you understand how windows form draws and redraws content to itself. By understanding this we can then work on the more complicated and fun programs in the future. We will build a good base with this knowledge and then apply those to make other programs and project in the future.

Lesson Objectives –

  1. Animate an IMAGE using paint event and timer
  2. Bounce the animated IMAGE on all 4 sides of the screen
  3. Reverse the speed and velocity of the object when either up/down/left or right side of the screen is reached
  4. test out the image transparency while working with multiple backgrounds in the project

Video

Download Images and Backgrounds here

Source Code –

namespace Paint_Movement_Project_MOO_ICT
{
    public partial class Form1 : Form
    {

        int positionX = 0;
        int positionY = 0;
        int speedY = 5;
        int speedX = 5;
        int height = 150;
        int width = 150;

        Image square;

        public Form1()
        {
            InitializeComponent();

            square = Properties.Resources.transparentSquare;
        }

        private void MovementTimerEvent(object sender, EventArgs e)
        {
            positionX += speedX;
            positionY += speedY;

            if (positionX + width > this.ClientSize.Width || positionX < 1) 
            { 
                speedX = -speedX; 
            } 
            else if (positionY + height > this.ClientSize.Height || positionY < 1)
            {
                speedY = -speedY;
            }


            this.Invalidate();
        }

        private void FormPaintEvent(object sender, PaintEventArgs e)
        {
            Graphics Canvas = e.Graphics;
            Canvas.DrawImage(square, positionX, positionY, width, height);
        }
    }
}




Comments are closed.