因为在.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