이미지의
경우 속도가 느리기 때문에 대부분 비동기 형태로 웹서버에서 받아와야 합니다.
iOS의 경우 GCD를
제공합니다. 닷넷의 경우 await/async를 결합해서
보다 쉽게 사용할 수 있습니다.
<?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:DemoBacktoWeb" x:Class="DemoBacktoWeb.DemoBacktoWebPage">
<ContentPage.Padding>
<OnPlatform x:TypeArguments="Thickness"
iOS="0, 20, 0, 0" />
</ContentPage.Padding>
<StackLayout>
<Grid VerticalOptions="FillAndExpand">
<Label x:Name="errorLabel"
HorizontalOptions="Center"
VerticalOptions="Center" />
<ActivityIndicator IsRunning="{Binding Source={x:Reference image},
Path=IsLoading}" />
<Image x:Name="image" />
</Grid>
<Button Text="Load Bitmap"
HorizontalOptions="Center"
Clicked="OnLoadButtonClicked" />
</StackLayout>
</ContentPage>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:DemoBacktoWeb" x:Class="DemoBacktoWeb.DemoBacktoWebPage">
<ContentPage.Padding>
<OnPlatform x:TypeArguments="Thickness"
iOS="0, 20, 0, 0" />
</ContentPage.Padding>
<StackLayout>
<Grid VerticalOptions="FillAndExpand">
<Label x:Name="errorLabel"
HorizontalOptions="Center"
VerticalOptions="Center" />
<ActivityIndicator IsRunning="{Binding Source={x:Reference image},
Path=IsLoading}" />
<Image x:Name="image" />
</Grid>
<Button Text="Load Bitmap"
HorizontalOptions="Center"
Clicked="OnLoadButtonClicked" />
</StackLayout>
</ContentPage>
using System.Net;
namespace DemoBacktoWeb
{
public partial class DemoBacktoWebPage : ContentPage
{
public DemoBacktoWebPage()
{
InitializeComponent();
}
async void OnLoadButtonClicked(object sender, EventArgs args)
{
try
{
Stream stream =
await GetStreamAsync("https://developer.xamarin.com/demo/IMG_1996.JPG");
image.Source = ImageSource.FromStream(() => stream);
}
catch (Exception exc)
{
errorLabel.Text = exc.Message;
}
}
async Task<Stream> GetStreamAsync(string uri)
{
TaskFactory factory = new TaskFactory();
WebRequest request = WebRequest.Create(uri);
WebResponse response = await factory.FromAsync<WebResponse>(request.BeginGetResponse,
request.EndGetResponse, null);
return response.GetResponseStream();
}
}
}
namespace DemoBacktoWeb
{
public partial class DemoBacktoWebPage : ContentPage
{
public DemoBacktoWebPage()
{
InitializeComponent();
}
async void OnLoadButtonClicked(object sender, EventArgs args)
{
try
{
Stream stream =
await GetStreamAsync("https://developer.xamarin.com/demo/IMG_1996.JPG");
image.Source = ImageSource.FromStream(() => stream);
}
catch (Exception exc)
{
errorLabel.Text = exc.Message;
}
}
async Task<Stream> GetStreamAsync(string uri)
{
TaskFactory factory = new TaskFactory();
WebRequest request = WebRequest.Create(uri);
WebResponse response = await factory.FromAsync<WebResponse>(request.BeginGetResponse,
request.EndGetResponse, null);
return response.GetResponseStream();
}
}
}
댓글 없음:
댓글 쓰기
참고: 블로그의 회원만 댓글을 작성할 수 있습니다.