首页 > 代码库 > winform图片旋转

winform图片旋转

01.//可以实现任意角度的旋转,旋转出现的角落空白可以选择填充的颜色。

02. 
03. 
04.using System;
05. 
06.using System.Drawing;
07.using System.Drawing.Drawing2D;
08.using System.Drawing.Imaging;
09.using System.Text;
10.using System.Windows.Forms;
11. 
12.namespace bitmaprerote
13.{
14.public partial class Form1 : Form
15.{
16.public Form1()
17.{
18.InitializeComponent();
19.}
20.public static Bitmap KiRotate(Bitmap bmp, float angle, Color bkColor)
21.{
22.int w = bmp.Width + 2;
23.int h = bmp.Height + 2;
24. 
25.PixelFormat pf;
26. 
27.if (bkColor == Color.Transparent)
28.{
29.pf = PixelFormat.Format32bppArgb;
30.}
31.else
32.{
33.pf = bmp.PixelFormat;
34.}
35. 
36.Bitmap tmp = new Bitmap(w, h, pf);
37.Graphics g = Graphics.FromImage(tmp);
38.g.Clear(bkColor);
39.g.DrawImageUnscaled(bmp, 1, 1);
40.g.Dispose();
41. 
42.GraphicsPath path = new GraphicsPath();
43.path.AddRectangle(new RectangleF(0f, 0f, w, h));
44.Matrix mtrx = new Matrix();
45.mtrx.Rotate(angle);
46.RectangleF rct = path.GetBounds(mtrx);
47. 
48.Bitmap dst = new Bitmap((int)rct.Width, (int)rct.Height, pf);
49.g = Graphics.FromImage(dst);
50.g.Clear(bkColor);
51.g.TranslateTransform(-rct.X, -rct.Y);
52.g.RotateTransform(angle);
53.g.InterpolationMode = InterpolationMode.HighQualityBilinear;
54.g.DrawImageUnscaled(tmp, 0, 0);
55.g.Dispose();
56.tmp.Dispose();
57.return dst;
58.}
59.private void button2_Click(object sender, EventArgs e)
60.{
61.Bitmap map = new Bitmap("F:\\hj.jpg");
62.this.pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
63.map = KiRotate(map, 30, Color.Pink);
64.pictureBox1.Image = map;
65.}
66.}
67.}

winform图片旋转