C#WPF - 并非所有图像都显示在网格上

时间:2014-11-20 23:11:28

标签: c# wpf random bitmap grid

我无法一次性加载所有网格点。我有一个5x5网格,它打算在随机点加载25个随机图像。有25个图像,它应该填满整个网格。

我无法弄清楚当我装载25或装载较少时有空位的原因。我有一个图像在整个网格中重复,以避免图像格式相关的问题。我认为问题可能与Random类有关。

以下是代码:

private readonly Random _r = new Random();

public void LoadPictures(int numberOfPictures)
{
    // Create a 2d array of specified dimensions
    var picArr = new bool[5, 5]; 

    for (int j = 0; j < numberOfPictures; j++) 
    {
        // Get the images from the specified folder
        string[] imagePaths = Directory.GetFiles(
            Environment.CurrentDirectory + "/images");

        bool invalidPlacement = true; // default is true

        while (invalidPlacement)
        {
            var i = new Image();  

            try
            {
                // Load the image with a random Picture
                var uri = new Uri(imagePaths[_r.Next(0, imagePaths.Length)]);
                i.Source = new BitmapImage(uri);
                Debug.WriteLine(uri.AbsolutePath);
                i.Width = ImageWidth;
                i.Height = ImageHeight;                    
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            // Put it somewhere
            int row = _r.Next(5);
            Thread.Sleep(TimeSpan.FromMilliseconds(50));
            int col = _r.Next(5);

            // Check to see if there is something there
            if (picArr[col, row] == false)
            {
                picArr[col, row] = true;
                Grid.SetColumn(i, col);
                Grid.SetRow(i, row);
                Background2.Children.Add(i);
                AnimateControl(i, 100, 100, 0, 0);
                invalidPlacement = false;
            }
        }
    }
}

0 个答案:

没有答案