1.创建一个list,用于记录缩放状态。
public List<int> zoomList = new List<int>();
2.创建一个位图文件,用于存放缩放后的最新图片。
public Bitmap globalBitMap;
3.图片缩小代码:
zoomList.Add(-1);
if (zoomList.Count > 0 && zoomList.Count(p => p > 0) == zoomList.Count(p => p < 0))
{
Bitmap bm = globalBitMap;
panel1.BackgroundImage = bm;
zoomList.Clear();
}
else
{
Bitmap bm = panel1.BackgroundImage as Bitmap;
panel1.BackgroundImage = GetResizeImage(bm, 1 / 0.9);
}
4.图片扩大的代码:
zoomList.Add(1);
if (zoomList.Count > 0 && zoomList.Count(p => p > 0) == zoomList.Count(p => p < 0))
{
Bitmap bm = globalBitMap;
panel1.BackgroundImage = bm;
zoomList.Clear();
}
else
{
Bitmap bm = panel1.BackgroundImage as Bitmap;
panel1.BackgroundImage = GetResizeImage(bm, 0.9);
}
5.缩放函数的代码:
private Bitmap GetResizeImage(Bitmap bm, double times)
{
int nowWidth = (int)(bm.Width / times);
int nowHeight = (int)(bm.Height / times);
Bitmap newbm = new Bitmap(nowWidth, nowHeight);//新建一个放大后大小的图片
if (times >= 1 && times <= 1.1)
{
newbm = bm;
}
else
{
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(newbm);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.DrawImage(bm, new System.Drawing.Rectangle(0, 0, nowWidth, nowHeight), new System.Drawing.Rectangle(0, 0, bm.Width, bm.Height), GraphicsUnit.Pixel);
g.Dispose();
}
return newbm;
}
6.说明:
上述缩放的比例是0.9或10/9, 使用的是gdi+封装的缩放函数。
panel1 是一个panel控件,这里缩放的是它的背景图。 缩放后直接体现在背景图上。