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);
        }
    }
}
相关推荐
self_myth11 小时前
[特殊字符] 深入理解操作系统核心特性:从并发到分布式,从单核到多核的全面解析
windows·macos·wpf·harmonyos
c#上位机12 小时前
wpf之TextBlock
c#·wpf
玉面小君2 天前
从 WPF 到 Avalonia 的迁移系列实战篇6:ControlTheme 和 Style区别
c#·wpf·avalonia
c#上位机2 天前
wpf之Border
c#·wpf
SunflowerCoder2 天前
WPF迁移avalonia之图像处理(一)
图像处理·wpf·avalonia
周杰伦fans2 天前
WPF中的DataContext以及常见的绑定方式
wpf
没有bug.的程序员3 天前
Redis 数据结构全面解析:从底层编码到实战应用
java·数据结构·redis·wpf
somethingGoWay3 天前
wpf 自定义输入ip地址的文本框
wpf
秋月的私语3 天前
Wpf程序屏幕居中问题修复全记录
wpf
我要打打代码3 天前
WPF启动窗体的三种方式
wpf