因為在.NET Framework下的許多API在.NET CF上不能使用,客觀上增加了圖檔任意角度旋轉的難度,在經過幾天的研究之後,并且結合網上的資料,算法如下,僅供參考,由該代碼引起的任何問題本人不負任何責任,并遵照開源代碼傳播協定。
private Bitmap GetNewBmp(ref Bitmap oldbmp, int angle)
{
angle = angle % 360;
//if (angle > 180) angle = 360 - angle;
//if (angle < -180) angle = 360 + angle;
float radians = (float)(2 * Math.PI * angle) / 360;
float cos = (float)Math.Cos(radians);
float sin = (float)Math.Sin(radians);
float Point1x = -oldbmp.Height * sin;
float Point1y = oldbmp.Height * cos;
float Point2x = oldbmp.Width * cos - oldbmp.Height * sin;
float Point2y = oldbmp.Height * cos + oldbmp.Width * sin;
float Point3x = oldbmp.Width * cos;
float Point3y = oldbmp.Width * sin;
float minx = Math.Min((float)0, Math.Min(Point1x, Math.Min(Point2x, Point3x)));
float miny = Math.Min((float)0, Math.Min(Point1y, Math.Min(Point2y, Point3y)));
float maxx = Math.Max(Point1x, Math.Max(Point2x, Point3x));
float maxy = Math.Max(Point1y, Math.Max(Point2y, Point3y));
int DestBmpWidth, DestBmpHeight;
if (angle > 90 && angle < 180)
DestBmpWidth = (int)Math.Ceiling(-minx);
else
DestBmpWidth = (int)Math.Ceiling(maxx - minx);
if (angle > 180 && angle < 270)
DestBmpHeight = (int)Math.Ceiling(-miny);
else
DestBmpHeight = (int)Math.Ceiling(maxy - miny);
Bitmap newbmp = new Bitmap(DestBmpWidth, DestBmpHeight);
for (int x = 0; x < DestBmpWidth; ++x)
{
for (int y = 0; y< DestBmpHeight; ++y)
{
int srcbmpX = (int)((x + minx) * cos + (y + miny) * sin);
int srcbmpY = (int)((y + miny) * cos - (x + minx) * sin);
if (srcbmpX >= 0 && srcbmpX < oldbmp.Width
&& srcbmpY >= 0 && srcbmpY < oldbmp.Height)
newbmp.SetPixel(x, y, oldbmp.GetPixel(srcbmpX, srcbmpY));
}
}
return newbmp;
}
轉自:http://www.devdiv.net/bbs/viewthread.php?tid=11713