首页 > 解决方案 > 如何以编程方式在 PictureBox 中实现背景滚动?

问题描述

我的程序中有一个pictureBox。这pictureBox是我的其他控件的“无限”工作区域(当我位于其中的一些控件pictureBox接近pictureBox边界时,它的宽度和高度一直在增长)。我自己以编程方式实现了滚动条pictureBox,它只是在pictureBox. 现在我也想实现可滚动的背景。我希望在滚动时更改背景位置以及控件scrollBar。我为此创建了代码(我简化了它以便于阅读。这只是水平的逻辑。我在事件有效scrollBar时调用它):ScrollBar

public Bitmap DrawImageUnscaled(int x, int y, int width, int height)
{
//this is the part of the image that will be cropped
    Bitmap croppedPartBitmpap = new Bitmap(width, height);
    Rectangle croppedPartRectangle = new Rectangle(x, y, width, height);

    using (var g = Graphics.FromImage(croppedPartBitmpap))
    {
//BigBitmap - original background
        g.DrawImage(this.BigBitmap, 0, 0, croppedPartRectangle, GraphicsUnit.Pixel);
    }
//this is the part of the image that will left 
    Bitmap leftPartBitmap = new Bitmap(this.PanelWidth - width, height);
    Rectangle leftPartRectangle = new Rectangle(width, y,this.PanelWidth - width, height);
    using (var g = Graphics.FromImage(leftPartBitmap))
    {
        g.DrawImage(this.BigBitmap, 0, 0, leftPartRectangle, GraphicsUnit.Pixel);
    }

//this is the merged image
    Bitmap mergedBitmap = new Bitmap(this.PanelWidth, this.PanelHeight);
    using (var g = Graphics.FromImage(mergedBitmap))
    {
        g.DrawImage(leftPartBitmap, 0, 0);
        g.DrawImage(croppedPartBitmpap, leftPartBitmap.Width, 0);
    }
    return mergedBitmap;
}

当我滚动这个pictureBox区域时,程序正在裁剪超出边界的部分背景,然后将其与留在屏幕上的部分合并。它工作正常,但它需要太多内存,可能需要 2gb 甚至更多。你能帮我避免使用如此巨大的记忆吗?也许整个逻辑错了,我应该为此尝试更好的解决方案?

标签: c#winforms

解决方案


推荐阅读