.NET CF C# 位图的任意角度旋转

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值