C#窗体绘制缓慢

本文关键字:缓慢 体绘制 窗体 | 更新日期: 2023-09-27 18:21:20

我在Visual Studio 2012上制作了一个应用程序,并试图加快表单的绘制时间。

我有一个主表单,里面有一个容器,根据工具条的选择,新表单会显示在里面。它很有魅力,但问题是,无论电脑有多好(在不同的电脑上试用),都需要花很多时间来绘制,而问题似乎是背景。

我已经为主表单、表单中的容器以及我项目中的所有表单设置了背景图像,所以当它们出现时,背景图像不会被剪切,而是继续图像。但是,如果不是用背景来拍照,而我把背面留成白色,对所有人来说,主要的形式、容器和形式,它就像一种魅力。

我在网上读到过关于在表单中设置双缓冲区的内容,但它没有任何作用,它需要同样的时间。

有什么建议吗?提前感谢!

C#窗体绘制缓慢

您可以通过手动绘制背景来提高速度。这很有帮助,因为它允许您禁用基础背景色,这只会浪费时间,因为它无论如何都会被图像覆盖。

// Reference to manually-loaded background image
Image _bmp;
// In your constructor, set these styles to ensure that the background
// is not going to be automatically erased and filled with a color
public Form1() {
    InitializeComponent();
    SetStyle(
        ControlStyles.Opaque |
        ControlStyles.OptimizedDoubleBuffer | 
        ControlStyles.AllPaintingInWmPaint, true);
    // Load background image
    _bmp = Image.FromFile("c:''path''to''background.bmp");
}
// Override OnPaint to draw the background
protected override void OnPaint(PaintEventArgs e) {
    var g = e.Graphics;
    var srcRect = new Rectangle(0, 0, _bmp.Width, _bmp.Height);
    int startY = Math.Max(0, (e.ClipRectangle.Top / _bmp.Height) * _bmp.Height);
    int startX = Math.Max(0, (e.ClipRectangle.Left / _bmp.Width) * _bmp.Width);
    for (int y = startY; y < e.ClipRectangle.Bottom; y+= _bmp.Height)
        for (int x = startX; x < e.ClipRectangle.Right; x += _bmp.Width)
        {
            var destRect = new Rectangle(x, y, _bmp.Width, _bmp.Height);
            g.DrawImage(_bmp, destRect, srcRect, GraphicsUnit.Pixel);
        }
    base.OnPaint(e);
}