首页 > 解决方案 > 从 URL 加载图像并带有引用标题

问题描述

我需要从我的 CDN 下载静态图像并将它们显示在我的 Xamarin.Forms 视图中。我是 Xamarin 的新手,我很难弄清楚如何从 HTTP 请求中提取的字节数组中加载图像。

我的视图中有以下 XAML:

    <ListView ItemsSource="{Binding Images}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ImageCell ImageSource="{Binding .}">
                    
                </ImageCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

在我后面的代码中,我正在获取图像并尝试绑定到ImageSource实例集合。

    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        public ObservableCollection<ImageSource> Images { get; set; } = new ObservableCollection<ImageSource>();

        protected override async void OnAppearing()
        {
            base.OnAppearing();

            var client = new HttpClient();
            client.DefaultRequestHeaders.Add("Referer", "https://foo.bar/");
            var response = await client.GetAsync("https://foo.bar/library/5.jpg");

            byte[] image = await response.Content.ReadAsByteArrayAsync();
            var imageSource = ImageSource.FromStream(() => new MemoryStream(image));
            this.Images.Add(imageSource);
        }
    }

当我这样做时,StackLayout 中的图像是空的。我知道我可以改为绑定到一个 URL,ImageSource 可以为我下载它,但我需要传递一个ReferrerHeader。我无论如何都看不到强制 XAML视图允许自定义标头,如果我在后面的代码中Image实例化一个实例,我也看不到这样做的方法。ImageSource

当我阅读它的文档时ImageSource,听起来它只支持 URI、文件、流和应用程序资源来加载图像。因为我有一个字节数组,所以我将它包装在 a 中MemoryStream并调用ImageSource.FromStream. 虽然应用程序运行时没有加载任何内容 -ImageCell是空的。

我知道图像已下载。我将其转换byte[]为 Base64 字符串,然后将其放入Base64 to Image Decoder。图像加载没有问题,所以我知道它正在正确下载。我不明白的是为什么我不能让图像在ImageSource.

我也尝试只使用普通Image控件并遇到同样的问题。

    <ScrollView>
        <ContentView>
            <StackLayout BindableLayout.ItemsSource="{Binding Images}" Orientation="Horizontal">
                <BindableLayout.ItemTemplate>
                    <DataTemplate>
                        <Image Source="{Binding}"></Image>
                    </DataTemplate>
                </BindableLayout.ItemTemplate>
            </StackLayout>
        </ContentView>
    </ScrollView>

我在这里做错了什么,还是从互联网上动态下载带有特殊标题的图像,这是我在 Xamarin.Forms 中无法做到的?

标签: xamarin.formsimagesource

解决方案


尝试添加 this.BindingContext = this;页面构造函数。

   public MainPage()
   {
        InitializeComponent();

        this.BindingContext = this;
   }

推荐阅读