首页 > 解决方案 > WPF 在 ImageBox 中显示较大图像的一部分

问题描述

我来自 Winforms,试图在 WPF 中重写一个程序,我想显示整个图像的某个部分,这取决于我用于列表的 Id,我加载了整个图像的每个部分。我是能够在 Winforms 中成功完成,但我想使用 Controls.Image 在 WPF 中执行相同的任务。这是我在 Winforms 中所做的。

PictureBox picBox;
List<Image> tileImageList;
Image FullImage;

public TileFrame(PictureBox pbox)
{        
    picBox = pbox;

    FullImage = picBox.Image; //The source of the picBox is set to the full image on init
    tileImageList = new List<Image>();

    PopTileList();
}

void PopTileList()
{
    const int SIZE = 32;
    Bitmap bitFullImage = new Bitmap(FullImage);

    for (int y = 0; y < 48; y++)
    {
        for (int x = 0; x < 64; x++)
        {
            var portion = bitFullImage.Clone(new Rectangle((x * SIZE), (y * SIZE), SIZE, SIZE), bitFullImage.PixelFormat);

            tileImageList.Add(portion);             
        }
    }

    picBox.Image = tileImageList[10];//The first image that shows when this is done
}

public void ShowTilePic(int selectedId)
{            
    picBox.Image = tileImageList[--selectedId];         
}

由于正在显示的图像将根据列表框的选定项而变化,因此 tileImageList 对于关联列表框选定索引和 tileImageList 索引至关重要。我搜索的其他答案似乎比我在这里所做的要复杂得多。在 WPF 和代码中是否有一种简单的方法可以做到这一点?

标签: c#wpf

解决方案


NVM 我想通了。

List<CroppedBitmap> tileImageList;
Image imageBox;

public TileFrame(MainWindow mWindow)
{
    tileImageList = new List<CroppedBitmap>();
    imageBox = mWindow.ImageBox;

    PopTileList();
}

void PopTileList()
{
    const int SIZE = 32;

    var bitmapImage = (BitmapSource)imageBox.Source;         

    for (int y = 0; y < 48; y++)
    {
        for (int x = 0; x < 64; x++)
        {
            var portion = new CroppedBitmap(bitmapImage, new Int32Rect((x * SIZE), (y * SIZE), SIZE, SIZE));                       
            tileImageList.Add(portion);                 
        }
    }        
}

public void ShowTilePic(int selectedId)
{
    imageBox.Source = tileImageList[selectedId];
}

推荐阅读