Moving a rectangle around the screen with the Matrix class.

ddanbe 0 Tallied Votes 876 Views Share

The matrix class in .NET is not a full featured matrix class as mathematicians would like to see it, still you can do amazing things with it.
Create a new windows form application.
Fill in the code and you are ready to experiment.
In the code I do something with a translate transform, but you could try to use rotate for instance. Have fun!

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {          
        public Form1()
        {
            InitializeComponent();           
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            Pen myPen = new Pen(Color.Blue, 1);
            Pen myPen2 = new Pen(Color.Red, 1);
            Rectangle R = new Rectangle(20, 20, 100, 50);
            // Draw a rectangle to the screen before applying the
            // transform.           
            e.Graphics.DrawRectangle(myPen, R);          
            System.Threading.Thread.Sleep(500); 
            MoveRect(e.Graphics, myPen2, R, 20, 0);   
        }

        private void MoveRect(Graphics G, Pen P, Rectangle R, int Xdist, int Ydist)
        {
            //Erase rectangle
            Pen eraser = new Pen(this.BackColor);
            G.DrawRectangle(eraser, R);
            // Create a matrix and translate it.
            Matrix myMatrix = new Matrix();

            for (int i = 0; i < Xdist; i++)
            {
                System.Threading.Thread.Sleep(10 + i); //slow down
                Ydist = i;
                myMatrix.Translate(i, Ydist);
                // Draw the Points to the screen again after applying the
                // transform.
                G.DrawRectangle(eraser, R); //first erase the existing rectangle
                G.Transform = myMatrix;               
                G.DrawRectangle(P, R);
            }
        }   
    }
}