2011-11-01 91 views
3

我使用下面的代码通过以中心点为原点的角度旋转图像。使用c中的平移变换顺时针和逆时针旋转图像#

private Bitmap rotateImage(Bitmap b, float angle) 
{ 
     Bitmap returnBitmap = new Bitmap(b.Width, b.Height); 
     Graphics g = Graphics.FromImage(returnBitmap); 
     g.TranslateTransform((float)b.Width/2, (float)b.Height/2); 
     g.RotateTransform(angle); 
     g.TranslateTransform(-(float)b.Width/2,-(float)b.Height/2); 
     g.DrawImage(b, new Point(0, 0)); 
     return returnBitmap; 
} 

,就会出现问题,当我尝试旋转之后将图像恢复到其初始的角度performed.I打算通过的角度再次旋转图像来做到这一点(360 anglerotated),但这不是工作和图像的边缘似乎被削减。 有没有更好的解决方案来旋转c#中的图像。我只是想旋转图像到一个角度而没有向两侧弯曲,然后以对角度旋转图像以取消所施加的旋转,因此前一图像被恢复。

+0

似乎目标图像必须大于源代码并将其绘制在中心。 –

+0

它被切割的边缘或角落? – leppie

+0

@leppie是的。角落被切断。 – techno

回答

2

首先,正如评论中所述,您需要创建一个更大的目标位图来适应旋转的位图。这将让你正确的新大小:

public Size SizeAfterRotation(Size sz, float angle) 
{ 
    var m = new Matrix(); 
    m.Rotate(angle); 
    var pts = new[] 
        { 
         new Point(sz.Width, sz.Height), 
         new Point(sz.Width, 0) 
        }; 
    m.TransformPoints(pts); 
    return new Size(
     Math.Max(Math.Abs(pts[0].X), Math.Abs(pts[1].X)), 
     Math.Max(Math.Abs(pts[0].Y), Math.Abs(pts[1].Y))); 
} 

然后,作为恢复(回转动)的位图,我不会reccomand您尝试这样做。尝试保持原来的位图。恢复它会很棘手,如果你成功了,反正你会失去图像质量。