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);
        }
    }
}
相关推荐
码界奇点7 小时前
基于eBPF技术的高性能网络防火墙系统设计与实现
开发语言·网络·毕业设计·php·wpf·go语言·源代码管理
cjp56011 小时前
022.WPF 封装TextBox控件限制只输入数字自定义属性
wpf
cjp56011 小时前
021.WPF 以MVVM模式控制combox控件显示/隐藏
wpf
小北方城市网1 天前
Redis 分布式锁高可用实现:从原理到生产级落地
java·前端·javascript·spring boot·redis·分布式·wpf
流水线上的指令侠1 天前
补充说明——针对《C#:从 0 到 1 创建基于 NUnit + FlaUI 的 WPF UI 自动化测试项目》
功能测试·ui·c#·自动化·wpf
流水线上的指令侠1 天前
C# 实战:从 0 到 1 搭建基于 NUnit + FlaUI 的 WPF UI 自动化测试项目
功能测试·ui·c#·自动化·wpf·visual studio
贾修行1 天前
.NET 全栈开发学习路线:从入门到分布式
c#·.net·wpf·asp.net core·web api·winforms·services
晓13131 天前
第四章:Redis实战应用及常见问题(下篇)
java·数据库·缓存·wpf
掘根2 天前
【jsonRpc项目】客户端的Requestor模块,RpcCaller模块
wpf
FuckPatience2 天前
WPF ListBoxItem绑定自己在ListBox中的顺序
wpf