[英]C# - WPF - Set random picture to <Image>
如何将随机图片设置为 WPF <Image>
?
在我的代码中,我有 4 张图片。
函数img1_Loaded_1
像这样设置图像的来源:
问题是我希望 2 张图片具有相同的图片。 例如 img1 和 img4 会有相同的图片,而 image2 会有不同的图片,而 img3 也会有不同的图片。 此时我是这样制作的,但我想将此图片动态设置为 img1、img2 等。 我还想随机分配这 4 张图像中的哪 2 张具有相同的图片。
任何想法我怎么能做到这一点?
快速地将这些基本代码放在一起,希望能让您走上正轨。 代码应该位于 Window_Loaded 或另一个类似的高级容器中,因为它只需要调用一次。 潜在地,您可以执行其他操作,例如使用 LINQ 过滤列表(例如,选择图像控件将使源为空)。 如果您有任何问题,请告诉我!
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//Set up lists to track which images / image controls have been used .. image resources and image controls will be removed from the relevant list once used.
int imageCount = 4;
IList<string> imageNames = new List<string>(imageCount) { "Image0", "Image1", "Image2", "Image3" };
IList<Image> imageControls = new List<Image>(imageCount) { img1, img2, img3, img4 };
//Pick an image resource at random to use as the one that will appear twice.
Random random = new Random();
int duplicatedImageIndex = random.Next(0, imageCount - 1);
Uri duplicatedImageUri = new Uri("/rnd_pic;component/Images/" + imageNames[duplicatedImageIndex] + ".jpg", UriKind.RelativeOrAbsolute);
//Select a random image control for first instance of image resource to be duplicated, then remove control from list to ensure it's not re-used.
int firstDuplicatedImageControlIndex = random.Next(0, imageCount - 1);
imageControls[firstDuplicatedImageControlIndex].Source = new BitmapImage(duplicatedImageUri);
imageControls.RemoveAt(firstDuplicatedImageControlIndex);
//Select a random image control for second instance of image resource to be duplicated, then remove control & image resource from relevant list to ensure they're not re-used.
int secondDuplicatedImageControlIndex = random.Next(0, --imageCount - 1);
imageControls[secondDuplicatedImageControlIndex].Source = new BitmapImage(duplicatedImageUri);
imageControls.RemoveAt(secondDuplicatedImageControlIndex);
imageNames.RemoveAt(duplicatedImageIndex);
//loop through remaining image controls setting one of the remaining random images, removing control & image resource from relevant list as you go.
while (imageControls.Any())
{
int randomUpperBound = --imageCount - 1;
int nextRandomImageIndex = random.Next(0, randomUpperBound);
int imageControlIndex = random.Next(0, randomUpperBound);
Uri nextImageUri = new Uri("/rnd_pic;component/Images/" + imageNames[nextRandomImageIndex] + ".jpg", UriKind.RelativeOrAbsolute);
imageControls[imageControlIndex].Source = new BitmapImage(nextImageUri);
imageControls.RemoveAt(imageControlIndex);
imageNames.RemoveAt(nextRandomImageIndex);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.