WPF中图片的宫格显示

1.解释说明

  • 使用ScrollViewer控件来达到滑动的效果

  • 使用WrapPanel的自动换行特性,保证图片在占满横向空间后自动往下排布

  • 使用foreach的方法来游历所有的图片url

2.xaml代码示例

cs 复制代码
<Grid>
    <ScrollViewer VerticalScrollBarVisibility="Auto">
        <WrapPanel Name="imageWrapPanel" Orientation="Horizontal" Margin="10">
            <!-- 图片将动态添加到这里 -->
        </WrapPanel>
    </ScrollViewer>
</Grid>

3.cs代码示例

cs 复制代码
//加载url转换成BitmapImage
private async Task<BitmapImage> LoadImageFromUrl(string url)
{
    try
    {
        using (HttpClient client = new HttpClient())
        {
            byte[] imageBytes = await client.GetByteArrayAsync(url);
            using (var stream = new System.IO.MemoryStream(imageBytes))
            {
                BitmapImage bitmapImage = new BitmapImage();
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = stream;
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapImage.EndInit();
                return bitmapImage;
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error loading image: {ex.Message}");
        return null;
    }
}


//显示图片
private async void LoadImagesFromServer()
{
    // 模拟从服务器获取图片URL列表
    string[] imageUrls = new string[]
    {
       "https://example1.png",
       "https://example2.png",
       "https://example3.png",
        // 添加更多图片URL
    };

    foreach (var imageUrl in imageUrls)
    {
        BitmapImage bitmapImage = await LoadImageFromUrl(imageUrl);
        if (bitmapImage != null)
        {
            Image image = new Image
            {
                Source = bitmapImage,
                Width = 200, // 设置图片宽度
                Height = 200, // 设置图片高度
                Margin = new Thickness(5) // 设置图片间距
            };
            imageWrapPanel.Children.Add(image);
        }
    }
}
相关推荐
一见已难忘10 小时前
基于 Harmony 6.0 应用的宠物寄养预约系统实现
wpf·宠物
fl17683110 小时前
基于C#WPF实现的内存加速球清理类似360加速球内存清理
开发语言·c#·wpf
李高钢11 小时前
【WPF】高级 UI 与性能优化实战:从卡顿到丝滑
ui·性能优化·wpf
Chris _data1 天前
WPF 上位机开发学习笔记 - 第四天
笔记·学习·wpf
李高钢1 天前
除了 IDE,C#/WPF 开发者每天离不开的 10 个工具
ide·c#·wpf
李高钢2 天前
用 JetBrains Rider 写 WPF 的 15 个高效技巧:从 VS 转过来也值得看
wpf
李高钢2 天前
【WPF】MVVM 与数据绑定实战:从原理到完整项目
wpf
李高钢3 天前
【WPF】从 Avalon 到 .NET 10:WPF 平台演进史与特性全览
.net·wpf
李高钢3 天前
WPF MVVM Light 入门:从零到Hello World
c#·wpf
李高钢3 天前
WPF MVVM Light(三):RelayCommand 命令与 Messenger 消息
前端·c#·wpf