如何在图片框中旋转图像

我正在制作一个winforms应用程序。 我希望实现的function之一是在家庭forms上的旋转装置。

装载主页时,应将鼠标hover在齿轮的图片上,并应将其旋转到位。

但到目前为止,我所拥有的只是RotateFlip而且只是翻转图片。

当鼠标hover在它上面时,有没有办法让齿轮转动到位?

我到目前为止的代码是:

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; } 

就像我说的,我只想转动装备。 我试图在Windows窗体应用程序中执行此操作。 使用C#。 框架4

您必须使用Timer来创建Image旋转。 没有用于旋转的内置方法。

创建全局计时器:

 Timer rotationTimer; 

在窗体的构造函数中初始化计时器并创建PictureBox MouseEnterMouseLeave事件:

 //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; 

然后创建他们的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(); } 

您可以像这样使用Graphics.RotateTransform方法; 我使用双缓冲面板,一个Timer和两个类变量..

 Bitmap bmp; float angle = 0f; private void Form1_Load(object sender, EventArgs e) { bmp = new Bitmap(yourGrarImage); int dpi = 96; using (Graphics G = this.CreateGraphics()) dpi = (int)G.DpiX; bmp.SetResolution(dpi, dpi); panel1.ClientSize = bmp.Size; } private void timer1_Tick(object sender, EventArgs e) { angle+=2; // set the speed here.. angle = angle % 360; panel2.Invalidate(); } private void panel1_Paint(object sender, PaintEventArgs e) { if (bmp!= null) { float bw2 = bmp.Width / 2f; // really ought.. float bh2 = bmp.Height / 2f; // to be equal!!! e.Graphics.TranslateTransform(bw2, bh2); e.Graphics.RotateTransform(angle); e.Graphics.TranslateTransform(-bw2, -bh2); e.Graphics.DrawImage(bmp, 0, 0); e.Graphics.ResetTransform(); } } private void panel1_MouseLeave(object sender, EventArgs e) { timer1.Stop(); } private void panel1_MouseHover(object sender, EventArgs e) { timer1.Start(); timer1.Interval = 10; // ..and/or here } 

确保图像是方形的,中间有齿轮!! 这是一个很好的:

在此处输入图像描述在此处输入图像描述齿轮有15个齿轮

这是一个无闪烁的双缓冲面板:

 public class Display : Panel { public Display() { this.DoubleBuffered = true; } }