我想下载Xamarin中的图像并显示它,但我有一个错误,说
"无法等待无效">
行上的
;
var imageBytes = await webClient.DownloadDataAsync(url);
这是代码:
public async void DownloadImages()
{
var webClient = new WebClient();
var url = new Uri("myurl.jpg");
var imageBytes = await webClient.DownloadDataAsync(url);
if (imageBytes != null && imageBytes.Length > 0)
{
GridRectangleImage.Source = ImageSource.FromStream(() => new MemoryStream(imageBytes));
}
}
如果使用DownloadDataAsync:下载完成时,将引发DownloadDataCompleted
事件。下载的数据在Result
属性中可用
public async void DownloadImages()
{
var webClient = new WebClient();
var url = new Uri("myurl.jpg");
webClient.DownloadDataAsync(url);
webClient.DownloadDataCompleted += WebClient_DownloadDataCompleted;
}
private void WebClient_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
var imageBytes = e.Result;
if (imageBytes != null && imageBytes.Length > 0)
{
GridRectangleImage.Source = ImageSource.FromStream(() => new MemoryStream(imageBytes));
}
}
如果使用DownloadDataTaskAsync,任务对象上的Result
属性将返回一个包含下载资源的Byte数组:
public async void DownloadImages()
{
var webClient = new WebClient();
var url = new Uri("myurl.jpg");
var imageBytes = await webClient.DownloadDataTaskAsync(url);
if (imageBytes != null && imageBytes.Length > 0)
{
GridRectangleImage.Source = ImageSource.FromStream(() => new MemoryStream(imageBytes));
}
}
@Hugokis
按照以下步骤,下载图像并显示Xamarin
步骤1:-创建Xamarin项目。
步骤2:-添加Xamarin Support v7 AppCompat库。添加引用Android.Support.v7。AppCompat使用NuGet Package Manager
步骤3:-在app.xaml文件中添加代码:
<?xml version="1.0" encoding="utf-8" ?>
<resources>
<style name="MyTheme" parent="MyTheme.Base">
</style>
<!--Base theme applied no matter what API-->
<style name="MyTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="windowNoTitle">true</item>
<!--We will be using the toolbar so no need to show ActionBar-->
<item name="windowActionBar">false</item>
<!--Set theme color from http://www.google.com/design/spec/style/color.html#color-co-->
<!--Color Primary is used for default action bar backround-->
<item name="colorPrimary">#009688</item>
<!--Color Primary Dark is use for status bar-->
<item name="colorPrimaryDark">#1976D2</item>
<!--ColorAccent is used as the default value for
ColorControlActivat1ed which is used to tint widgts-->
<item name="colorAccent">#FF4081</item>
<item name="colorControlHighlight">#FF4081</item>
<!--You can also set ColorControlNormal ColorControlActivated
ColorControlHihglight colorSwitchThumbNormal.-->
</style>
</resources>
步骤4:-将一个新文件夹添加到名为-v21的资源文件夹中。类似地,在values-v21文件夹-style.xml中添加一个新的XAML文件,并添加以下代码。
Xaml代码:
<?xml version="1.0" encoding="utf-8" ?>
<resources>
<!--
Base Application theme for API 21+. this theme
replaces MyTheme from res/style.xml on API 21+ devices-->
<style name="MyTheme" parent="MyTheme.Base">
<item name="android:windowContentTransitions">true</item>
<item name="android:windowAllowEnterTransitionOverlap">true</item>
<item name="android:windowAllowReturnTransitionOverlap">true</item>
<item name="android:windowSharedElementEnterTransition">@android:transition/move</item>
<item name="android:windowSharedElementExitTransition">@android:transition/move</item>
<item name="android:windowTranslucentStatus">true</item>
</style>
</resources>
步骤5:-编写DownloadImageFromUrl类
C#代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Graphics.Drawables;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Java.IO;
using Java.Net;
namespace SaveWithProgress
{
public class DownloadImageFromUrl : AsyncTask<string, string, string>
{
private ProgressDialog pDialog;
private ImageView imgView;
private Context context;
public DownloadImageFromUrl(Context context, ImageView imgView)
{
this.context = context;
this.imgView = imgView;
}
protected override void OnPreExecute()
{
pDialog = new ProgressDialog(context);
pDialog.SetMessage("Downloading file. Please wait...");
pDialog.Indeterminate = false;
pDialog.Max = 100;
pDialog.SetProgressStyle(ProgressDialogStyle.Horizontal);
pDialog.SetCancelable(true);
pDialog.Show();
base.OnPreExecute();
}
protected override void OnProgressUpdate(params string[] values)
{
base.OnProgressUpdate(values);
pDialog.SetProgressNumberFormat(values[0]);
pDialog.Progress = int.Parse(values[0]);
}
protected override void OnPostExecute(string result)
{
string strongPath = Android.OS.Environment.ExternalStorageDirectory.Path;
string filePath = System.IO.Path.Combine(strongPath, "download.jpg");
pDialog.Dismiss();
imgView.SetImageDrawable(Drawable.CreateFromPath(filePath));
}
protected override string RunInBackground(params string[] @params)
{
string strongPath = Android.OS.Environment.ExternalStorageDirectory.Path;
string filePath = System.IO.Path.Combine(strongPath, "download.jpg");
int count;
try
{
URL url = new URL(@params[0]);
URLConnection connection = url.OpenConnection();
connection.Connect();
int LengthOfFile = connection.ContentLength;
InputStream input = new BufferedInputStream(url.OpenStream(), LengthOfFile);
OutputStream output = new FileOutputStream(filePath);
byte[] data = new byte[1024];
long total = 0;
while ((count = input.Read(data)) != -1 )
{
total += count;
PublishProgress(""+(int)((total / 100) / LengthOfFile));
output.Write(data, 0, count);
}
output.Flush();
output.Close();
input.Close();
}
catch (Exception e)
{
}
return null;
}
}
}
步骤6:-主布局打开解决方案资源管理器->项目名称->资源->布局->Main.axml。打开此主布局文件并添加以下代码。
Xaml代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:fitsSystemWindows="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
local:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
<Button
android:text="Download Image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnDownload" />
<ImageView
android:src="@android:drawable/ic_menu_gallery"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/imageView" />
</LinearLayout>
步骤7:-主活动类C#代码:
using Android.App;
using Android.Widget;
using Android.OS;
using Android.Support.V7.App;
namespace SaveWithProgress
{
[Activity(Label = "SaveWithProgress", MainLauncher = true , Theme ="@style/MyTheme")]
public class MainActivity : AppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
var btnDownload = FindViewById<Button>(Resource.Id.btnDownload);
var imageView = FindViewById<ImageView>(Resource.Id.imageView);
btnDownload.Click += delegate
{
DownloadImageFromUrl download = new DownloadImageFromUrl(this, imageView);
download.Execute("http://www.qygjxz.com/data/out/244/4304228-wallpaper-phone-hd.jpg");
};
}
}
}
步骤8:-设备的权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
我希望上面的代码对你有用。
谢谢。