【发布时间】:2020-08-02 19:51:42
【问题描述】:
这里有新的 xamarin 程序员。我需要使用 URL 显示来自 Internet 的漫画图像,但不知何故,系统一直告诉我指向 url 的链接不起作用,但我不知道为什么当我实例化一个新的 UriImageSource 时。
我的第一种方法是尝试使用 BitMapImage 显示图像,但它仅适用于 WindowsForms 或 WPF,因此如果 UriImageSource 不适合我,我也需要替代方法。顺便说一句,我在 Mac 上。
这是 xaml:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Weather_App.MainPage">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<StackLayout Grid.Row="1" Orientation="Horizontal" HorizontalOptions="Center">
<Image x:Name="backgroundImage" Margin="20"/>
</StackLayout>
</Grid>
</ContentPage>
这是 MainPage.cs:
using Xamarin.Forms;
namespace Weather_App
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
private int maxNumber = 0;
private int currentNumber = 0;
public MainPage()
{
InitializeComponent();
ViewModel.ApiHelper.InitializeClient();
string url = Convert.ToString(ComicProcessor.LoadComic());
backgroundImage.Source = new UriImageSource
{
Uri = new Uri(url),
CachingEnabled = false,
CacheValidity = TimeSpan.FromHours(1)
};
}
}
}
最后,这是 viewmodel/LoadComic 方法。我最初尝试返回漫画而不是 url,但由于 Mac 不存在 BitMapImage,所以我返回了 url,因为我认为我可以将它用于 UriImageSource 实例。漫画属性包括一个整数 Num 和一个字符串 Img。
namespace Weather_App
{
public class ComicProcessor
{
public static int MaxComicNumber { get; set; }
public async static Task<string> LoadComic(int comicNumber = 0)
{
string url = "";
if (comicNumber > 0)
{
url = $"https://xkcd.com/{comicNumber}/info.0.json";
}
else
{
url = $"https://xkcd.com/info.0.json";
}
using (HttpResponseMessage response = await ViewModel.ApiHelper.ApiClient.GetAsync(url))
{
if (response.IsSuccessStatusCode)//If response successful do something then
{
// Takes data in as json and converted it to the type you have given and match anything that it finds
ComicModel comic = await response.Content.ReadAsAsync<ComicModel>();
if (comicNumber == 0)
{
MaxComicNumber = comic.Num;
}
return url;
}
else
{
// Outputs reason why it wasn't successful
throw new Exception(response.ReasonPhrase);
}
}
}
}
}
【问题讨论】: