C#Xamarin从url加载图片

时间:2017-04-07 06:52:04

标签: c# image xamarin xamarin.forms

我正在尝试从url字符串加载图像。下面的代码是一个项目数组,其中Photo是加载图像的内容。通常,我从我的硬盘中包含了图像,然后通过Photo = "image_name.jpg"

加载了该​​图像

这是第一个代码:

public MainPageViewModel()
{        
    items.Add(new CardStackView.Item() { Name = "Title 1", Photo = " xxx ", Description = "Desc 1" });
    items.Add(new CardStackView.Item() { Name = "Title 2", Photo = " xxx ", Description = "Desc 2" });
    items.Add(new CardStackView.Item() { Name = "Title 3", Photo = " xxx ", Description = "Desc 3" });
    items.Add(new CardStackView.Item() { Name = "Title 4", Photo = " xxx ", Description = "Desc 4" });
    items.Add(new CardStackView.Item() { Name = "Title 5", Photo = " xxx ", Description = "Desc 5" });
    items.Add(new CardStackView.Item() { Name = "Title 6", Photo = " xxx ", Description = "Desc 6" });
}

我希望xxx成为我的网址示例https://i.vimeocdn.com/portrait/58832_300x300

这段代码是我显示图像的地方:

Photo = new Image()
{
    InputTransparent = true,
    Aspect = Aspect.Fill,
    Scale = 0.95
};

view.Children.Add(Photo,
                  Constraint.RelativeToParent((parent) => { double w = parent.Width * 1; return ((parent.Width - w) / 2); }),
                  Constraint.Constant(10),
                  Constraint.RelativeToParent((parent) => { return parent.Width; }),
                  Constraint.RelativeToParent((parent) => { return (parent.Height* 0.80); }));  

请注意,这两段代码不是在同一个文件中,而是在两个单独的文件中。

我希望这不是重复,因为我无法找到解决问题的方法。

2 个答案:

答案 0 :(得分:1)

您需要设置Source元素的Image

Photo = new Image()
{
    InputTransparent = true,
    Aspect = Aspect.Fill,
    Scale = 0.95,
    Source = "https://your_image_url.com/the_image.png"
};

答案 1 :(得分:0)

我建议您使用Binding,基本上您只需要设置Source的值。尝试以下方法:

  <Image Source="{Binding ImageUrl}" WidthRequest="80" HorizontalOptions="Start" VerticalOptions="Start" />