Rotate Square object in win forms using graphics

Follow Steps given below:


(1) open new Win form and import following namespace.give reference when necessary.



using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;

(2) Add timer control in your form.


(3)Copy below code in the form constructor.



public Form1()
{
InitializeComponent();

BufferedGraphicsContext context = BufferedGraphicsManager.Current;
context.MaximumBuffer = new Size(this.Width + 1, this.Height + 1);
bufferedGraphics = context.Allocate(this.CreateGraphics(),
new Rectangle(0, 0, this.Width, this.Height));
timer.Enabled = true;
timer.Tick += OnTimer;
timer.Interval = 20; // 50 images per second.
timer.Start();
}


(4)Add following code in timer control's tick event.



private void OnTimer(object sender, System.EventArgs e)
{
angle++;
if (angle > 359)
angle = 0;
Graphics g = bufferedGraphics.Graphics;
g.Clear(Color.Black);
Matrix matrix = new Matrix();
matrix.Rotate(angle, MatrixOrder.Append);
matrix.Translate(this.ClientSize.Width / 2,
this.ClientSize.Height / 2, MatrixOrder.Append);
g.Transform = matrix;
g.FillRectangle(Brushes.Azure, -100, -100, 200, 200);
bufferedGraphics.Render(Graphics.FromHwnd(this.Handle));
}


(5) Save your win form and run it.


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: