【问题标题】:Randomly place images in multiple Image controls在多个图像控件中随机放置图像
【发布时间】:2014-01-13 17:57:11
【问题描述】:

我正在 WPF 中创建一个简单的“配对”游戏。我在 MainWindow 上有 12 个图像控件。我需要做的是使用 OpenFileDialog 选择多个图像(可以少于全部 6 个),然后将它们随机放入图像控件中。每张图片应该出现两次。我怎么能做到这一点?我在这里停留了一段时间,目前只有以下代码。我不是在寻求解决方案,我只需要一些关于如何处理这个问题的指示。谢谢。

  > public ObservableCollection<Image> GetImages()
    {
        OpenFileDialog dlg = new OpenFileDialog();
        dlg.Multiselect = true;

        ObservableCollection<Image> imagesList = new ObservableCollection<Image>();

        if (dlg.ShowDialog() == true)
        {
            foreach (String img in dlg.FileNames)
            {
                Image image = new Image();

                image.Name = "";
                image.Location = img;
                imagesList.Add(image);
            }
        }
        return imagesList;
    }

【问题讨论】:

  • 基本思路:从对话框中获取文件名,然后将它们两次(!)放入一个列表(我们称之为 fileList)。现在运行一个生成图像的循环。在循环中,生成一个 0 到 fileList.Count-1 范围内的随机数。从 fileList 中获取相应的文件名元素以创建图像,并从 fileList 中删除该元素。当 fileList 为空时,循环结束。
  • 会试一试。感谢您的提示。

标签: c# wpf


【解决方案1】:

有很多方法可以实现您所需的结果。一个好方法是使用Directory.GetFiles method,它将返回string 文件路径的集合:

string [] filePaths = Directory.GetFiles(targetDirectory);

然后您可以使用一种方法来随机化集合的顺序。来自 DotNETPerls 上的 C# Shuffle Array 页面:

public string[] RandomizeStrings(string[] arr)
{
    List<KeyValuePair<int, string>> list = new List<KeyValuePair<int, string>>();
    // Add all strings from array
    // Add new random int each time
    foreach (string s in arr)
    {
        list.Add(new KeyValuePair<int, string>(_random.Next(), s));
    }
    // Sort the list by the random number
    var sorted = from item in list
             orderby item.Key
             select item;
    // Allocate new string array
    string[] result = new string[arr.Length];
    // Copy values to array
    int index = 0;
    foreach (KeyValuePair<int, string> pair in sorted)
    {
        result[index] = pair.Value;
        index++;
    }
    // Return copied array
    return result;
}

然后添加您的重复文件路径,再次重新随机排序并使用项目填充您的 UI 属性:

string[] filePathsToUse = new string[filePaths.Length * 2];
filePaths = RandomizeStrings(filePaths);
for (int count = 0; count < yourRequiredNumber; count++)
{
    filePathsToUse.Add(filePaths(count));
    filePathsToUse.Add(filePaths(count));
}
// Finally, randomize the collection again:
ObservableCollection<string> filePathsToBindTo = new 
    ObservableCollection<string>(RandomizeStrings(filePathsToUse));

当然,您也可以通过许多其他方式来实现,有些更容易理解,有些更有效。只需选择一种您觉得舒服的方法即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-10
    • 1970-01-01
    • 1970-01-01
    • 2014-10-10
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    相关资源
    最近更新 更多