近期做抽奖软件,作出后发现加载图片和不加载图片,程序刷新的很慢,且卡顿的很严重;严重影响用户体验;
经过网络大量资料查询,尝试了一下方法:
方法一:预加载图片方法
在窗体加载后,将图片读进来,然后释放资源;代码如下:
string path = System.Environment.CurrentDirectory + "\\backgroundImage.jpg";
Bitmap bm = new Bitmap(path);
Bitmap newBm = new Bitmap(bm);
bm.Dispose();
this.panel1.BackgroundImage = newBm;
this.panel1.BackgroundImageLayout = ImageLayout.Stretch;
this.BackgroundImage = newBm;
结果:效果不明显
方法二:图片加载采用容器panel
不设置窗体的背景图片,在窗体上放置panel,然后设置panel的背景图片
结果:无效
方法三:窗体启用双缓存
winform窗体属性直接设置即可,已可以通过以下代码设置
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.
SetStyle(ControlStyles.DoubleBuffer, true); // 双缓冲
结果:
效果不明显卡顿依旧
protected override CreateParams CreateParams
{
get
{
CreateParams paras = base.CreateParams;
paras.ExStyle |= 0x02000000;
return paras;
}
}
直接将此段代码,复制到对应窗体即可,
结果:效果没有改善
方法五:重新封装panel类
public class PanelEx : Panel
{
/// <summary>
/// OnPaintBackground 事件
/// </summary>
/// <param name="e"></param>
protected override void OnPaintBackground(PaintEventArgs e)
{
// 重载基类的背景擦除函数,
// 解决窗口刷新,放大,图像闪烁
return;
}
/// <summary>
/// OnPaint 事件
/// </summary>
/// <param name="e"></param>
protected override void OnPaint(PaintEventArgs e)
{
// 使用双缓冲
this.DoubleBuffered = true;
// 背景重绘移动到此
if (this.BackgroundImage != null)
{
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
e.Graphics.DrawImage(
this.BackgroundImage,
new System.Drawing.Rectangle(0, 0, this.Width, this.Height),
0,
0, this.BackgroundImage.Width, this.BackgroundImage.Height, System.Drawing.GraphicsUnit.Pixel);
}
base.OnPaint(e);
}
}
新建panel时,修改panel的类名为panelEx即可
this.panel1 = new LuckDrawForm.PanelEx();
this.panel1.BackColor = System.Drawing.Color.Transparent;
this.panel1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel1.Location = new System.Drawing.Point(0, 0);
private PanelEx panel1;
结果完美解决....http://www.cnblogs.com/candyzhmm/p/5961394.html
因篇幅问题不能全部显示,请点此查看更多更全内容