private void btnRotating_Click( object sender, EventArgs e ) { pbNewPicture.Image = Rotating((Bitmap)pbImage.Image, Convert.ToInt32( cmbAngle.SelectedItem.ToString() ) ); } public Bitmap Rotating(Bitmap bitmap,int angle) { angle = angle % 360;//弧度转换 double radian = angle * Math.PI / 180; double cos = Math.Cos( radian ); double sin = Math.Sin( radian ); //原图像的宽和高 int width=bitmap.Width; int height=bitmap.Height; int newWidth=(int)Math.Max(Math.Abs(width*cos-height*sin),Math.Abs(width*cos+height*sin)); int newHeight=(int)(Math.Max(Math.Abs(width*sin-height*sin),Math.Abs(width*sin+height*cos))); //目标位图 Bitmap newBitmap = new Bitmap(newWidth,newHeight); Graphics graphics = Graphics.FromImage( newBitmap ); graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear;//指定缩放算法 graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;//指定抗锯齿呈现图形边缘,用于平滑直线、曲线等 //计算偏移量 Point offset = new Point((newWidth-width)/2,(newHeight-height)/2); //构造图像显示区域:让图像的中心与窗口的中心点一致 Rectangle rectangle = new Rectangle(offset.X,offset.Y,width,height); Point center = new Point(rectangle.X+rectangle.Width/2,rectangle.Y+rectangle.Height/2); graphics.TranslateTransform( center.X, center.Y ); graphics.RotateTransform( 360 - angle ); //恢复图像在水平和垂直方向的平移 graphics.TranslateTransform( -center.X, -center.Y ); graphics.DrawImage( bitmap, rectangle ); //重置绘图的所有变换 graphics.ResetTransform(); graphics.Save(); return newBitmap; }
与真实的图像旋转相差一定的距离,继续努力中......