先看效果
平移
旋转
缩放
对应方法
平移
/// <summary>
///
/// </summary>
/// <param name="bmp">原始图像</param>
/// <param name="x">横向平移距离(像素)</param>
/// <param name="y">纵向平移距离(像素)</param>
/// <param name="bkColor"></param>
/// <returns></returns>
public static Bitmap Move(Bitmap bmp, int x, int y, Color bkColor)
{
Bitmap backBitmap = new Bitmap(bmp.Width + x, bmp.Height + y);
Graphics g = Graphics.FromImage(backBitmap);
g.Clear(bkColor);
g.DrawImageUnscaled(bmp, x, y);
g.Dispose();
return backBitmap;
}
旋转
/// <summary>
/// 旋转图像
/// </summary>
/// <param name="bmp">原始图像</param>
/// <param name="angle">旋转角度(角度制)</param>
/// <param name="backColor">背景色</param>
/// <returns>输出Bitmap</returns>
public static Bitmap Rotate(Bitmap bmp, float angle, Color backColor)
{
int w = bmp.Width + 2;
int h = bmp.Height + 2;
PixelFormat pf;
if (backColor == Color.Transparent)
{
pf = PixelFormat.Format32bppArgb;
}
else
{
pf = bmp.PixelFormat;
}
Bitmap tmp = new Bitmap(w, h, pf);
Graphics g = Graphics.FromImage(tmp);
g.Clear(backColor);
g.DrawImageUnscaled(bmp, 1, 1);
g.Dispose();
GraphicsPath path = new GraphicsPath();
path.AddRectangle(new RectangleF(0f, 0f, w, h));
Matrix mtrx = new Matrix();
mtrx.Rotate(angle);
RectangleF rct = path.GetBounds(mtrx);
Bitmap dst = new Bitmap((int)rct.Width, (int)rct.Height, pf);
g = Graphics.FromImage(dst);
g.Clear(backColor);
g.TranslateTransform(-rct.X, -rct.Y);
g.RotateTransform(angle);
g.InterpolationMode = InterpolationMode.HighQualityBilinear;
g.DrawImageUnscaled(tmp, 0, 0);
g.Dispose();
tmp.Dispose();
return dst;
}
缩放
/// <summary>
/// 缩放图像
/// </summary>
/// <param name="bitmap">原始图像</param>
/// <param name="scaleX">横向缩放(比例)</param>
/// <param name="scaleY">纵向缩放(比例)</param>
/// <returns></returns>
public static Bitmap Scale(Bitmap bitmap, float scaleX, float scaleY)
{
if (scaleX < 0) bitmap.RotateFlip(RotateFlipType.RotateNoneFlipX);
if (scaleY < 0) bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);
return new Bitmap(bitmap, new Size((int)Math.Abs(bitmap.Width * scaleX), (int)Math.Abs(bitmap.Height * scaleY)));
}