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属性对这种方法无效。

  • 相关阅读:
    vue-cli 2.x 项目优化之:引入本地静态库文件
    关联本地文件夹到 GitLab 项目
    react 子组件访问父组件的方法
    vue 和 react 组件间通信方法对比
    mobx-state-tree 知识点
    vue 下实现 echarts 全国到省份的地图下钻
    TweenMax 动画库,知识点
    mobx 知识点
    highcharts 知识点
    dependencies、devDependencies、webpack打包 的区别与联系
  • 原文地址:https://www.cnblogs.com/Mr-Owl/p/5336752.html
Copyright © 2011-2022 走看看