2014-01-11 44 views
1

導致的大小我有在C#中旋轉的圖像下面的代碼:獲取RotateTransform

private Bitmap RotateImage(Bitmap b, float angle) 
{ 
    //create a new empty bitmap to hold rotated image 
    Bitmap returnBitmap = new Bitmap(b.Width, b.Height); 

    //make a graphics object from the empty bitmap 
    Graphics g = Graphics.FromImage(returnBitmap); 
    //move rotation point to center of image 
    g.TranslateTransform((float)returnBitmap.Width/2, (float)returnBitmap.Height/2); 

    //rotate 
    g.RotateTransform(angle); 
    //move image back 
    g.TranslateTransform(-(float)b.Width/2, -(float)b.Height/2); 
    //draw passed in image onto graphics object 
    g.DrawImage(b, new Rectangle(new Point(0, 0), new Size(b.Width, b.Height))); 
    return returnBitmap; 
} 

它時,它超過了原來的界限的作品非常好,但它的剪輯的結果。

據我所知,我必須將rotateBitmap的大小設置爲旋轉後的圖像大小。但是,我如何找到結果會有多大,以相應地設置新位圖的大小?

+0

看一看我的意見[這裏](https://stackoverflow.com/questions/5172906/C-旋轉圖形/ 48725273#48725273) –

回答

1

您需要旋轉你的原始圖像的四角和計算新座標邊框:

private static Bitmap RotateImage(Image b, float angle) 
    { 
     var corners = new[] 
      {new PointF(0, 0), new Point(b.Width, 0), new PointF(0, b.Height), new PointF(b.Width, b.Height)}; 

     var xc = corners.Select(p => Rotate(p, angle).X); 
     var yc = corners.Select(p => Rotate(p, angle).Y); 

     //create a new empty bitmap to hold rotated image 
     Bitmap returnBitmap = new Bitmap((int)Math.Abs(xc.Max() - xc.Min()), (int)Math.Abs(yc.Max() - yc.Min())); 
     ... 
    } 

    /// <summary> 
    /// Rotates a point around the origin (0,0) 
    /// </summary> 
    private static PointF Rotate(PointF p, float angle) 
    { 
     // convert from angle to radians 
     var theta = Math.PI*angle/180; 
     return new PointF(
      (float) (Math.Cos(theta)*(p.X) - Math.Sin(theta)*(p.Y)), 
      (float) (Math.Sin(theta)*(p.X) + Math.Cos(theta)*(p.Y))); 
    } 
0

畢達哥拉斯。在90/270度的角度,它可以是任何地方,從原始到sqrt(w^2 + h^2)。我敢打賭,它是由正弦(最大值爲90)決定的。

相關問題