星期一, 7月 10, 2017

[X.Form] Image - 網路存取

UriImageSource 可以自動下載 image 來顯示並提供 cache 機制,可以透過屬性設定
  • CachingEnabled:預設為 true
  • CacheValidity:TimeSpan,預設為一天

  • xaml 呼叫
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:ImagePractice"
             x:Class="ImagePractice.Internet">
    <ContentPage.Content>
        <StackLayout
            HorizontalOptions="Center"
            VerticalOptions="Center">

        <Label Text="Web Demo" FontAttributes="Bold"></Label>
        <Image 
            x:Name="imgWeb" 
            Aspect="AspectFit"
            Source="https://www.xamarin.com/content/images/pages/forms/example-app.png"></Image>

        </StackLayout>
    </ContentPage.Content>
</ContentPage>
  • C# Code 呼叫
xaml layout
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:ImagePractice"
             x:Class="ImagePractice.Internet">
    <ContentPage.Content>
        <StackLayout
            HorizontalOptions="Center"
            VerticalOptions="Center">

        <Label Text="Web Demo" FontAttributes="Bold"></Label>
        <Image 
            x:Name="imgWeb" 
            Aspect="AspectFit"
            ></Image>

        </StackLayout>
    </ContentPage.Content>
</ContentPage>
C# Code
namespace ImagePractice
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class Internet : ContentPage
    {
        public Internet ()
        {
            InitializeComponent ();

            // 方法一:直接給 url 會自動轉換為 uri
            imgWeb.Source = "https://www.xamarin.com/content/images/pages/forms/example-app.png";

            // 方法二
            imgWeb.Source = ImageSource.FromUri(new Uri("https://www.xamarin.com/content/images/pages/forms/example-app.png"));

            // 方法三
            imgWeb.Source = new UriImageSource()
            {
                Uri = new Uri("https://www.xamarin.com/content/images/pages/forms/example-app.png"),
                CachingEnabled = true , // 預設為 true
                CacheValidity = new TimeSpan(0, 5, 0) // 預設快取是一天
            };
        }
    }
}
結果:換張煙火圖來表示

[X.Form] Image  - 網路存取

沒有留言:

張貼留言