Rotating a line in C#
Recently I had a problem that required me to do a rotation of a line keeping the original point fixed. A rotation is a movement of an object in a circular motion, mathematically a rotation is a rigid body movement which, unlike a translation, keeps a point fixed.
public partial class Rotate : Form
{
public Bitmap image;
public Graphics gra;
public int angle = 10;
public int step = 0;
public int radius = 150;
public System.Timers.Timer timer;
public Rotate()
{
InitializeComponent();
image = new Bitmap(400, 300);
gra = Graphics.FromImage(image);
gra.Clear(Color.DarkBlue);
pictureBox1.Image = image;
}
private void button1_Click(object sender, EventArgs e)
{
if (timer == null)
{
timer = new System.Timers.Timer(50);
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Start();
}
}
private void button2_Click(object sender, EventArgs e)
{
if (timer != null)
{
timer.Stop();
timer = null;
}
}
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
gra.Clear(Color.DarkBlue);
PointF point1 = new PointF(200, 150);
PointF point2 = new PointF();
point2.X = radius * (float)Math.Cos(DegreesToRadians(angle * step)) + 200;
point2.Y = radius * (float)Math.Sin(DegreesToRadians(angle * step)) + 150;
gra.DrawLine(new Pen(Color.White), point1, point2);
step++;
pictureBox1.Image = image;
}
private double DegreesToRadians(double angle)
{
return angle * Math.PI / 180.0;
}
}
Code Explanation:
public Bitmap image;
public Graphics gra;
public int angle = 10;
public int step = 0;
public int radius = 150;
public System.Timers.Timer timer;
public Rotate()
{
InitializeComponent();
image = new Bitmap(400, 300)
gra = Graphics.FromImage(image);
gra.Clear(Color.DarkBlue);
pictureBox1.Image = image;
}
To start with the step alongside the angle variable is used to calculate the angle witch the line must be rotated, a step of 36 will result in a full rotation of the line (10 * 36 = 360 degrees), in the class constructor we simply initialize the variables and set the default background color of the image to DarkBlue
gra.Clear(Color.DarkBlue);
PointF point1 = new PointF(200, 150);
PointF point2 = new PointF();
point2.X = radius * (float)Math.Cos(DegreesToRadians(angle * step)) + 200;
point2.Y = radius * (float)Math.Sin(DegreesToRadians(angle * step)) + 150;
gra.DrawLine(new Pen(Color.White), point1, point2);
step++;
This is where the magic happens, we calculate the X and Y position and we draw the line the + 200/150 at the end represents the offset that we started with in point1.
Download the project here.
No related posts.
4 Comments
Trackbacks/Pingbacks
- Rotirea unei linii C# | WorldIT - [...] Articol original Area72. [...]

Very interesting post. Keep us posting buddy !
Really enjoyed it. Thank you!
Thanks for your good project.
I bless you alot.
By