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);
        }
    }
}
相关推荐
小二·16 小时前
MyBatis基础入门《十五》分布式事务实战:Seata + MyBatis 实现跨服务数据一致性
分布式·wpf·mybatis
helloworddm1 天前
UnregisterManyAsync
wpf
军训猫猫头1 天前
3.NModbus4 长距离多设备超时 C# + WPF 完整示例
c#·.net·wpf·modbus
Aevget1 天前
DevExpress WPF中文教程:Data Grid - 如何绑定到有限制的自定义服务(一)?
ui·.net·wpf·devexpress·ui开发·wpf界面控件
Macbethad1 天前
半导体设备工厂自动化软件技术方案
wpf·智能硬件
Macbethad1 天前
半导体设备报警诊断程序技术方案
wpf·智能硬件
Macbethad2 天前
技术方案:工业控制系统架构设计
wpf
狮恒2 天前
OpenHarmony Flutter 分布式数据持久化:跨设备数据一致性与同步方案
分布式·flutter·wpf·openharmony
狮恒3 天前
OpenHarmony Flutter 分布式数据管理:跨设备数据同步与一致性保障方案
分布式·flutter·wpf·openharmony
Macbethad3 天前
工业设备IO模拟程序
wpf