How to Rotate a Drawing in PictureBox
Rotating a drawing in a PictureBox is helpful for animation or when you don't want to display your drawing with its default rotation. A PictureBox is a Windows control that you use in programming for displaying images and drawings on a Form. To rotate a drawing, you need to first create a PictureBox and then link it to a Paint event-handler function, which will draw, translate and finally rotate the drawing inside the PictureBox.
Instructions
-
-
1
Open your source file in an editor such as Microsoft Visual Studio Express. The following example code will use C#, but with slight alterations it will work in other languages such as Visual Basic and C++.
-
2
Include the following namespaces at the top of your Form file with C# to access all the drawing methods by adding the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
-
-
3
Create a PictureBox object and initialize it by adding the following code with C# in the Form class:
private PictureBox my_pictureBox = new PictureBox();
private void Form1_Load()
{
my_pictureBox.Dock = DockStyle.Fill;
my_pictureBox.BackColor = Color.Black;
my_pictureBox.Paint += new System.Windows.Forms.PaintEventHandler(this.my_pictureBox_Paint);
this.Controls.Add(my_pictureBox);
}
The "PictureBox" will have a black background and its Paint event will be linked to the event handler method.
-
4
Rotate the drawing with the RotateTransform method by adding the following code with C# in the Form class:
private void my_pictureBox_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
e.Graphics.TranslateTransform(100.0F, 0.0F);
e.Graphics.RotateTransform(60.0F);
e.Graphics.DrawEllipse(new Pen(Color.White, 3), 0, 0, 150, 60);
}
The function draws a white ellipse, sets the rotation point and then rotates the drawing 60 degrees.
-
5
Save the source file and compile and run the program to view the rotated drawing in the PictureBox.
-
1