Xamarin Forms - 图像源无法从 url 工作

Lea*_*lan 8 xamarin.forms

我已将 Visual Studio 从 2017 (15.9.16) 更新到 2019 (16.3.1)。然后我在 2019 工作室打开旧的(2017)项目,在 Android 模拟器中运行,发现所有以 url 为源的图像都没有显示。我尝试了不同的变体,但没有任何帮助。

然后我创建了用于测试的空白应用程序:
App1 (.Net Standard 2.0) + App1.Android。

主页.xaml:

<StackLayout>
    <Label Text="Welcome to Xamarin.Forms!" 
       HorizontalOptions="Center"
       VerticalOptions="CenterAndExpand" />

    <Frame HeightRequest="200" BackgroundColor="#E7E7E7">
        <Image x:Name="myImage" Aspect="Fill" />
        <!--<Image Source="http://lealan.me/Content/images/typist/typist07.jpg" />-->
        <!--<Image>
            <Image.Source>
                <UriImageSource Uri="http://lealan.me/Content/images/typist/typist07.jpg" />
            </Image.Source>
        </Image>-->            
    </Frame>
</StackLayout>
Run Code Online (Sandbox Code Playgroud)

MainPage.xaml.cs:

public MainPage()
{
    InitializeComponent();

    var url = "http://lealan.me/Content/images/typist/typist07.jpg";

    // variant 1 (not worked)
    //this.myImage.Source = ImageSource.FromUri(new Uri(url));

    // variant 2 (not worked)
    //this.myImage.Source = new UriImageSource() { Uri = new Uri(url) };

    // variant 3 (only this variant worked)
    var byteArray = new WebClient().DownloadData(url);
    this.myImage.Source = ImageSource.FromStream(() => new MemoryStream(byteArray));

    // + see others variants in MainPage.xaml
}
Run Code Online (Sandbox Code Playgroud)

此外,我在“高级 Android 选项”中尝试了不同的“Http 客户端实现”,我什至尝试授予 android 应用程序的所有权限,但没有任何帮助。
(只有变体 3 有效,但对于 MVVM 绑定来说很重)

Ale*_*oma 14

我之前遇到过这个问题,它与服务器没有添加正确的标头有关。

我得到的最佳解决方案是创建一个下载图像的转换器。作为您的变体 3。

这是我所做的。

    public class ImageSourceConverter : IValueConverter
    {
        static WebClient Client = new WebClient();
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
             if (value == null)
                 return null;

             var byteArray = Client.DownloadData(value.ToString());
             return ImageSource.FromStream(() => new MemoryStream(byteArray));
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }


// And the xaml

<Image Source="{Binding ImageUrl, Converter={StaticResource ImageSourceConverter}}" />
Run Code Online (Sandbox Code Playgroud)


小智 7

你从视觉工作室的输出是什么。我在从传递的 uri 加载图像时遇到了类似的问题。结果证明它是清单中所需的标头。

<application
    android:usesCleartextTraffic="true">
            ...
</application>```
Run Code Online (Sandbox Code Playgroud)


小智 6

我遇到了同样的问题,并在这里找到了解决方案:https ://doumer.me/resolve-image-loading-error-in-xamarin-forms/

  1. 右键单击您的 Android 项目
  2. 选择属性
  3. 转到Android 选项
  4. 单击高级按钮
  5. HTTPClient更改为托管
  6. SSL/TLS 实现更改为Native TLS 1.2+
  7. 保存更改并运行您的项目。现在将加载来自 Uri 的图像