程序代码:
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
private Bitmap img;
private float rot = 0F;
/// <summary>
/// 图片
/// </summary>
public Bitmap Img
{
get { return img; }
set { img = value; }
}
/// <summary>
/// 旋转角度
/// </summary>
public float Rot
{
get { return rot; }
set
{
rot = value;
this.Invalidate();
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (this.img != null)
{
Graphics g = this.CreateGraphics();
if (rot != 0F)
{
g.DrawImage(ImageRotate(img, rot, this.BackColor), new Point(0, 0));
}
else
{
g.DrawImage(img, new Point(0, 0));
}
}
}
/// <summary>
/// 任意角度旋转
/// </summary>
/// <param name="bmp">原始图Bitmap </param>
/// <param name="angle">旋转角度 </param>
/// <param name="bkColor">背景色 </param>
/// <returns>输出Bitmap </returns>
public static Bitmap ImageRotate(Bitmap p_Image, float p_Angle, Color p_BlackColor)
{
int _Width = p_Image.Width + 2;
int _Height = p_Image.Height + 2;
PixelFormat _BitmapPixelFormat = PixelFormat.Format32bppArgb;
if (p_BlackColor != Color.Transparent) _BitmapPixelFormat = p_Image.PixelFormat;
Bitmap _OldBitmap = new Bitmap(_Width, _Height, _BitmapPixelFormat);
Graphics _Graphics = Graphics.FromImage(_OldBitmap);
_Graphics.Clear(p_BlackColor);
_Graphics.DrawImageUnscaled(p_Image, 1, 1);
_Graphics.Dispose();
GraphicsPath _Path = new GraphicsPath();
_Path.AddRectangle(new RectangleF(0f, 0f, _Width, _Height));
Matrix _Mtrx = new Matrix();
_Mtrx.Rotate(p_Angle);
RectangleF _Rect = _Path.GetBounds(_Mtrx);
Bitmap _NewBitmap = new Bitmap((int)_Rect.Width, (int)_Rect.Height, _BitmapPixelFormat);
_Graphics = Graphics.FromImage(_NewBitmap);
_Graphics.Clear(p_BlackColor);
_Graphics.TranslateTransform(-_Rect.X, -_Rect.Y);
_Graphics.RotateTransform(p_Angle);
_Graphics.InterpolationMode = InterpolationMode.HighQualityBilinear;
_Graphics.DrawImageUnscaled(_OldBitmap, 0, 0);
_Graphics.Dispose();
_OldBitmap.Dispose();
return _NewBitmap;
}
}
[
本帖最后由 xydddaxia 于 2011-9-28 13:44 编辑 ]