Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
678 views
in Technique[技术] by (71.8m points)

c# - How to rotate image in picture box

I am making a winforms application. One of the features I hope to implement is a rotating gear on the home form.

When the home form is loaded, you should hover over the picture of the gear, and it should rotate in place.

But all I have so far is the RotateFlip and that just flips the picture.

Is there a way to make the gear turn in place when the mouse is hovering over it?

The code I have so far is:

Bitmap bitmap1;
    public frmHome()
    {
        InitializeComponent();
        try
        {
            bitmap1 = (Bitmap)Bitmap.FromFile(@"gear.jpg");
            gear1.SizeMode = PictureBoxSizeMode.AutoSize;
            gear1.Image = bitmap1;
        }
        catch (System.IO.FileNotFoundException)
        {
            MessageBox.Show("There was an error." +
                "Check the path to the bitmap.");
        }
    }

    private void frmHome_Load(object sender, EventArgs e)
    {
        System.Threading.Thread.Sleep(5000);
    }

    private void frmHome_FormClosed(object sender, FormClosedEventArgs e)
    {
        Application.Exit();
    }

    private void pictureBox1_MouseHover(object sender, EventArgs e)
    {

        bitmap1.RotateFlip(RotateFlipType.Rotate180FlipY);
        gear1.Image = bitmap1;
    }

Like I said, I just want to turn the gear. I am trying to do this in a Windows Form application. Using C#. Framework 4

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You'll have to use Timer to create rotation of the Image. There is no built in method exists for rotation.

Create a global timer:

Timer rotationTimer;

Initialize timer in the constructor of the form and create PictureBox MouseEnter and MouseLeave events:

//initializing timer
rotationTimer = new Timer();
rotationTimer.Interval = 150;    //you can change it to handle smoothness
rotationTimer.Tick += rotationTimer_Tick;

//create pictutrebox events
pictureBox1.MouseEnter += pictureBox1_MouseEnter;
pictureBox1.MouseLeave += pictureBox1_MouseLeave;

Then create their Event Handlers:

void rotationTimer_Tick(object sender, EventArgs e)
{
    Image flipImage = pictureBox1.Image;
    flipImage.RotateFlip(RotateFlipType.Rotate90FlipXY);
    pictureBox1.Image = flipImage;
}

private void pictureBox1_MouseEnter(object sender, EventArgs e)
{
    rotationTimer.Start();
}

private void pictureBox1_MouseLeave(object sender, EventArgs e)
{
    rotationTimer.Stop();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...