尝试下载图像(可能是大图像)时,我面临OutOfMemoryException。我正在使用Xamarin.Android和PCL进行跨平台操作。
我要进行图像幻灯片放映。我在布局上叠加了数量有限的imageviews。刷出所有图像后,我会在这些图像视图中重新加载新图像。我已经完成了一个简单的项目,其中仅包含了该机制的令人耳目一新的部分。
请好,我是Android和Xamarin的初学者,这是代码:
MainActivity.cs:
[Activity(Label = "App1", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
private string[] urls = {
"http://momotaros.fr/wp-content/uploads/2014/01/One-Piece-5.png",
"http://www.infinite-rpg.com/wp-content/uploads/2014/09/Equipage.png",
"http://ekladata.com/ke33JLPQ2tTW1mTHCvPJBrKCPOE.jpg",
"http://ekladata.com/P2Q1mQuYTDbfEZnwb3f3IBsXoGM.png",
"http://ekladata.com/9QUE66iKU9uGUPVUdFmPF_ZIkK8.png"
};
protected override void OnCreate(Bundle bundle)
{
BlobCache.ApplicationName = "App1";
BlobCache.EnsureInitialized();
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
Button button = FindViewById<Button>(Resource.Id.MyButton);
ImageView image = FindViewById<ImageView>(Resource.Id.imageView1);
ImageView image2 = FindViewById<ImageView>(Resource.Id.imageView2);
ImageView image3 = FindViewById<ImageView>(Resource.Id.imageView3);
ImageView image4 = FindViewById<ImageView>(Resource.Id.imageView4);
ImageView image5 = FindViewById<ImageView>(Resource.Id.imageView5);
button.Click += (sender, e) =>
{
image.SetImageURL(urls[0]);
image2.SetImageURL(urls[1]);
image3.SetImageURL(urls[2]);
image4.SetImageURL(urls[3]);
image5.SetImageURL(urls[4]);
};
}
}
public static class BitmapExtensions
{
public static async void SetImageURL(this ImageView imageView, string url)
{
IBitmap bmp = await App1.Shared.ImageDownloadService.DownloadImage(url, imageView.Width, imageView.Height);
if (bmp != null)
{
imageView.SetImageDrawable(bmp.ToNative());
}
}
}
ImageDownloadService.cs(在PCL中):
public class ImageDownloadService
{
public static async Task<Splat.IBitmap> DownloadImage(string url, float desiredWidth, float desiredHeight)
{
return await BlobCache.LocalMachine.LoadImageFromUrl(url,false, desiredHeight:desiredHeight,desiredWidth: desiredWidth);
}
}
第一次单击该按钮时,将下载图像(即使我发现DDMS中的内存使用量有点高)。
但是对于下一次单击,监视内存使用情况,它会增加如地狱般的速度。
我当时在想,当我在那个imageView中设置一个新图像时,内存中以前的位图没有被处理掉,这在某处是一个很强的参考,但是我无法确定它到底在哪里。
感谢您为解决此问题或调试内存使用情况的任何技术(例如跟踪对象的创建位置和销毁位置的方法)提供的帮助。
感谢您花时间阅读这篇文章,希望您能对我有所帮助。
在您的内部,您BitmapExtensions
可能应该将其Bitmap
分配给后立即处置,因为之后ImageView
您将不会再将其用于其他任何用途。
public static class BitmapExtensions
{
public static async void SetImageURL(this ImageView imageView, string url)
{
using (IBitmap bmp = await App1.Shared.ImageDownloadService.DownloadImage(url, imageView.Width, imageView.Height))
{
if (bmp != null)
{
using(var nativeBmp = bmp.ToNative())
imageView.SetImageDrawable(nativeBmp);
}
}
}
}
您还应该确保该DownloadImage
方法可以捕获所有Exceptions
抛出的内部数据,否则,如果发生这种情况,您的时间将会很糟糕。
调用GC.Collect
不是必需的,因为这将迫使GC此时收集,这可能会使应用程序在执行操作时无响应。只要确保销毁所有参考资料,您就应该心满意足。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句