加载图像时出现 OutOfMemoryError

OutOfMemoryError when loading an image

我有一个简单的页面显示 image.The 来源是 URL

   var img = new Image ();
    var source = new UriImageSource {
        Uri = new Uri (string.Format ("http://xxxx.com/imagem/?{0}", url)),
            CachingEnabled = false
        };
        img .Source = source;

但是当我访问这个页面()时,第四次或第五次,我得到这个错误

java.lang.OutOfMemoryError
    at android.graphics.Bitmap.nativeCreate(Native Method)
    at android.graphics.Bitmap.createBitmap(Bitmap.java:928)
    at android.graphics.Bitmap.createBitmap(Bitmap.java:901)
    at android.graphics.Bitmap.createBitmap(Bitmap.java:868)
    at md5530bd51e982e6e7b340b73e88efe666e.ButtonDrawable.n_draw(Native Method)
    at 340b73e88efe666e.ButtonDrawable.draw(ButtonDrawable.java:49)
    at android.view.View.draw(View.java:15235)
    at android.view.View.getDisplayList(View.java:14141).....

我们 运行 遇到了一个非常相似的问题。它看起来 Xamarin has released some guidance on the issue,但它并不是真正面向 Xamarin Forms。基本上,在设置图像的来源之前,您需要决定是否应该按比例缩小,并手动进行。这可能需要自定义渲染器。

似乎 Xamarin Forms 应该为我们做些什么,但我想有时候你必须把坏事与好的一起接受。

Here Xamarin 论坛上有关于此问题的讨论。

更新: 我刚刚注意到你说这只会在第 4 次或第 5 次页面加载后发生。我们在解决该问题的页面上创建了一个解决方法。基本上,您必须将图像的 Source 设置回 null 并在页面消失时强制进行垃圾回收。像这样:

protected override void OnDisappearing ()
{
    base.OnDisappearing ();
    img.Source = null;
    GC.Collect ();
}

我不是那个 Xamarin.Forms 专家,但在 Xamarin.Android 和 Xamarin.iOS 上,在该代码周围使用 using 或处置图像(及其来源)是一种非常好的行为.原因是 .net GC 可能认为该对象非常小,因此他不需要立即释放它并保持引用,而底层本机实例是多个 MB 大。

手动调整图像大小(通过 GIMP 或其他图像编辑器)似乎对我有用。正如其他人提到的,在 OnDisappearing 中使用垃圾收集器也可能有所帮助。