Reputation: 75
I have a simple page that displays an image.The source is a 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;
but when I access this page (), the fourth time or the fifth it, I get this error
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).....
Upvotes: 5
Views: 2925
Reputation: 1967
Manually resizing the image (via GIMP or some other image editor) seemed to do the trick for me. As others have mentioned, using the garbage collector in OnDisappearing also may help.
Upvotes: 0
Reputation: 2892
We ran into a very similar issue. It appears Xamarin has released some guidance on the issue, but it's not really geared towards Xamarin Forms. Basically, before setting the source of the image, you need to decide whether it should be scaled down, and do it manually. This will likely require a Custom Renderer.
Seems like something Xamarin Forms should do for us, but sometimes you have to take the bad with the good I suppose.
Here is a discussion on the Xamarin Forums regarding this issue.
Update: I just noticed you said that this happens only after the 4th or 5th time the page is loaded. We created a workaround on the page that solved the issue. Basically, you have to set the image's Source back to null and force a garbage collection when the page is disappearing. Like this:
protected override void OnDisappearing ()
{
base.OnDisappearing ();
img.Source = null;
GC.Collect ();
}
Upvotes: 4
Reputation: 2879
I am not that Xamarin.Forms expert but on Xamarin.Android and Xamarin.iOS it is a very good behavior to use using around that code or to dispose the image (and its source). The reason for this is that the .net GC might think that the object is very small so he does not need to free it up immediately and keeps holding a reference while the underlaying native instance is multiple MB large.
Upvotes: 1