zoukankan      html  css  js  c++  java
  • Winform以任意角度旋转PictureBox中的图片的方法

    方法1:

      private void RotateFormCenter(PictureBox pb, float angle)
      {
                Image img = pb.Image;
                int newWidth = Math.Max(img.Height, img.Width);
                Bitmap bmp = new Bitmap(newWidth, newWidth);
                Graphics g = Graphics.FromImage(bmp);
                Matrix x = new Matrix();
                PointF point = new PointF(img.Width / 2f, img.Height / 2f);
                x.RotateAt(angle, point);
                g.Transform = x;
                g.DrawImage(img, 0, 0);
                g.Dispose();
                img = bmp;
                pb.Image = img;
      }
    

      该方法通过将图片转化为用于几何变换的3x3矩阵 对图片进行旋转。

      缺点:有时图片会越转越模糊。

    方法2:

    private void RotateFormCenter(PictureBox pb, float angle)
    {
                Graphics graphics = pb.CreateGraphics();
                graphics.Clear(pb.BackColor);
                //装入图片
                Bitmap image = new Bitmap(pb.Image);
                //获取当前窗口的中心点
                Rectangle rect = new Rectangle(0, 0, pb.Width, pb.Height);
                PointF center = new PointF(rect.Width / 2, rect.Height / 2);
                float offsetX = 0;
                float offsetY = 0;
                offsetX = center.X - image.Width / 2;
                offsetY = center.Y - image.Height / 2;
                //构造图片显示区域:让图片的中心点与窗口的中心点一致
                RectangleF picRect = new RectangleF(offsetX, offsetY, image.Width, image.Height);
                PointF Pcenter = new PointF(picRect.X + picRect.Width / 2,
                    picRect.Y + picRect.Height / 2);
                // 绘图平面以图片的中心点旋转
                graphics.TranslateTransform(Pcenter.X, Pcenter.Y);
                graphics.RotateTransform(angle);
                //恢复绘图平面在水平和垂直方向的平移
                graphics.TranslateTransform(-Pcenter.X, -Pcenter.Y);
                //绘制图片
                graphics.DrawImage(image, picRect);
    }

    通过操作Graphics进行图像旋转,使用时需要注意图片是按原始大小进行居中旋转  PictureBox的SizeMode属性对这种方法无效。

  • 相关阅读:
    多个tomcat配置,解决冲突问题
    多态-重载和覆载
    静态成员、静态类和枚举
    重复使用类--继承和组合
    建立更可靠的OOP程序-类和成员的访问控制
    用ps画一个Gif的小房子(1)
    在h5页面上添加音乐播放
    使用Object类为实例定义方法和属性
    使用 prototype 定义方法和属性
    使用 this 关键字定义方法和属性
  • 原文地址:https://www.cnblogs.com/Mr-Owl/p/5336752.html
Copyright © 2011-2022 走看看