How to rotate a drawn line by increasing the angle by using a timer?

eshesh michael 60 Reputation points
2023-04-29T08:44:48.55+00:00

The problem is that the line also get shorter and I want to keep the line length. when it's rotating.

I'm using the method DrawLine and call it in the pictureBox1 paint event and it's drawing a line.

now I want to rotate the line in a circle without changing the center point and without leave lines behind only to rotate that line with the same radius.

like a doppler effect just to imagine what I mean by rotating.

not sure if to use a timer for that and how to do it?

private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            Graphics mygraph = e.Graphics;
            mygraph.DrawLine(mypen, 250, 250, x, 150);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            x++;
            pictureBox1.Invalidate();
        }
Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,873 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,650 questions
{count} votes

Accepted answer
  1. Castorix31 83,206 Reputation points
    2023-04-30T08:45:08.7433333+00:00

    I used a .png in my test to avoid drawing the line.

    By drawing the line, you can do something like this with a Timer :

    At beginning (Form1_Load) :

                var timer1 = new System.Windows.Forms.Timer();
                timer1.Tick += new EventHandler(TimerEventProcessor);
                timer1.Interval = 10;
                timer1.Start();
    
    

    then :

            private void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
            {
                pictureBox1.Invalidate();
            }
    
            float m_nAngle = 0;
    
            private void pictureBox1_Paint(object sender, PaintEventArgs e)
            {
                var g = e.Graphics;
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.Clear(Color.Yellow);
                var rect = this.pictureBox1.ClientRectangle;
                g.TranslateTransform(rect.Left + rect.Width / 2, rect.Top + rect.Height / 2);
                g.RotateTransform(m_nAngle);
                m_nAngle += 1;
                if (m_nAngle >= 360) m_nAngle = 0;
                using (var penLine = new Pen(Color.Red, 2))
                    g.DrawLine(penLine, 0, 0, 0, -rect.Height / 2);           
            }
    

    Rotate_Line


0 additional answers

Sort by: Most helpful