dnennis
dnennis

Reputation: 140

Gauge Needle Pivot Point

My math skills are not good. I've searched the Internet and cannot figure this out.

I'm having a hard time trying to keep a speedometer type gauge needle positioned.

The gauge is half a circle or 180 degrees. The needle is a png image that is 10 pixels wide and 164 pixels high.

The gauge is 378 pixels wide and 226 pixels high.

Because I'm trying to rotate a tall rectangle the needle position must me recalculated.

Point pivotPoint = new Point(gauge.Width / 2, gauge.Height); 
double degrees = -45; // example where to point the needle

Can someone please give me some actual lines of C# code that will keep the needle png correctly positioned?

Your help is very much appreciated.

Upvotes: 1

Views: 1876

Answers (1)

TaW
TaW

Reputation: 54453

Here is some code that draws a rotated needle image onto a PictureBox with a gauge image.

I take the angle from a trackbar that goes from 0 to 180.

The Needle stands upright upside down:

  • The angle makes up for the 90° offset we begin with.
  • The rotation point of the needle should be with its origin.

The PictureBox.SizeMode is set to Autosize.

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    using (Bitmap needle =  new Bitmap("D:\\needle3.png" )  )
    {
        int angle = trBar_angle.Value;
        label1.Text = angle.ToString("###0°");

        // this is the offset after the translation
        Point targetPoint = new Point(-needle.Width / 2, needle.Width / 2);

        // shortcuts for the sizes
        Size nSize = needle.Size;
        Size pSize = pictureBox1.ClientSize;

        // this is the translation of the graphic to meet the rotation point
        int transX = pSize.Width / 2;
        int transY = pSize.Height - nSize.Width / 2;

        //set the rotation point and rotate
        e.Graphics.TranslateTransform( transX, transY );
        e.Graphics.RotateTransform(angle + 90); 

        // draw on the rotated graphics
        e.Graphics.DrawImage(needle, targetPoint);

        //reset everything
        e.Graphics.RotateTransform( -angle - 90); 
        e.Graphics.TranslateTransform( -transX, -transY );

    }

}

My needle: enter image description here and the result: enter image description here

I hope you have a nicer gauge than the one I made ;-)

Upvotes: 1

Related Questions