2016-09-17 72 views
2

我試圖製作一個在c#中使用定時器的輪子動畫(pictureBox上的輪子圖像)。旋轉圖像的在定時器上旋轉圖像而不混合圖像

方法:

public static Image RotateImage(Image img, float rotationAngle) 
    { 
     //create an empty Bitmap image 
     Bitmap bmp = new Bitmap(img.Width, img.Height); 

     //turn the Bitmap into a Graphics object 
     Graphics gfx = Graphics.FromImage(bmp); 

     //now we set the rotation point to the center of our image 
     gfx.TranslateTransform((float)bmp.Width/2, (float)bmp.Height/2); 

     //now rotate the image 
     gfx.RotateTransform(rotationAngle); 

     gfx.TranslateTransform(-(float)bmp.Width/2, -(float)bmp.Height/2); 

     //set the InterpolationMode to HighQualityBicubic so to ensure a high 
     //quality image once it is transformed to the specified size 
     gfx.InterpolationMode = InterpolationMode.HighQualityBicubic; 

     //now draw our new image onto the graphics object 
     gfx.DrawImage(img, new Point(0, 0)); 

     //dispose of our Graphics object 
     gfx.Dispose(); 

     //return the image 
     return bmp; 
    } 

//爲計時器滴答

private void timer1_Tick(object sender, EventArgs e) 
    { 
     float anglePerTick = 0; 
     anglePerTick = anglePerSec/1000 * timer1.Interval; 
     pictureBox1.Image = RotateImage(pictureBox1.Image, anglePerTick); 
    } 

代碼輪的圖像保持紡絲和顏色被混合,然後將圖像剛剛淡出。 我該如何解決這個問題?

+0

什麼是'anglePerSec'值,什麼是'timer1.Interval'值?你有沒有嘗試增加間隔? – SergeyS

回答

1

當圖像旋轉90度或90度的精確倍數的任何角度時,所有像素都會被保留,並且它們會移動到新的位置。但是,當以任何其他角度旋轉時,會發生重新採樣或近似,並且沒有單個像素會移動到新的像素位置,因爲像素位置是整數,但旋轉角度會產生非整數位置。這意味着每個像素的新顏色將來自預旋轉圖像的4和6像素之間的混合。這種混合會導致你看到的褪色。結果,反覆旋轉會引起越來越多的失真,直到圖像被顯着改變或者甚至被完全破壞。

解決方案是拍攝原始圖像的副本,然後每次恢復原始副本並以新角度旋轉。這樣你總是可以完成一次旋轉,而且不會累積扭曲。