大家好,正如标题所说,我正在尝试创建图像类型的数组并从文件夹中设置其中的图像源,因为文件夹中有 52 个 png,我不想一个一个地添加它们。所以有没有办法做到这一点 ? 这就是我到目前为止所得到的:
void DeckCard()
{
Image []Deck=new Image[52];
for(int i=0;i<=Deck.Length;i++)
{
Deck[i] = new Image();
LayoutRoot.Children.Add(Deck[i]);
Deck[i].Margin = new Thickness(0, 0, 0, 0);
Deck[i].Height = 400;
Deck[i].Width = 200;
}
}
附言文件夹位置是 Assets//Cards/(这里是图片)
最佳答案
如何使用 LINQ和 Directory.GetFiles :
Image[] deck = System.IO.Directory.GetFiles("Assets\\Cards\\")
.Select(file => System.Drawing.Image.FromFile(file))
.ToArray();
编辑
我从未开发过 Windows 应用商店应用程序,但这是我的尝试(请注意,我没有尝试编译以下代码):
Image[] cards = ApplicationData.Current.LocalFolder.GetFolderAsync("Assets\\Cards").GetResults()
.GetFilesAsync().GetResults()
.Select(file =>
{
using(IRandomAccessStream fileStream = file.OpenAsync(Windows.Storage.FileAccessMode.Read).GetResults())
{
Image image = new Image();
BitmapImage source = new BitmapImage();
source.SetSourceAsync(fileStream).GetResults();
image.Source = source;
// Modify Image properties here...
// image.Margin = new Thicknes(0, 0, 0, 0);
// ....
// You can also do LayoutRoot.Children.Add(image);
return image;
}
}).ToArray();
哎呀,太苛刻了!
当然可以使用 async/await 很好地重构这段代码。 .
关于c# - 使用给定文件夹中的源创建图像数组 C# Windows 桌面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33435820/