Xamarin.forms OutOfMemory error when using images

2019-06-12 07:51发布

I have a list view that I want to display an image for each item, loaded from a URL. If I use an ImageCell as the DataTemplate, it will load once and then if I try to load again I will get an OutOfMemory error.

I next tried the code from Introduction to Xamarin Forms page here http://developer.xamarin.com/guides/cross-platform/xamarin-forms/introduction-to-xamarin-forms/ to create a custom ViewCell

class MyViewCell : ViewCell
{
    public MyViewCell()
    {
        var image = new MyImage
        {
            HorizontalOptions = LayoutOptions.Start
        };
        image.SetBinding(Image.SourceProperty, new Binding("ImagePath"));
        image.WidthRequest = image.HeightRequest = 40;

        var nameLayout = CreateLayout();

        var viewLayout = new StackLayout()
        {
            Orientation = StackOrientation.Horizontal,
            Children = { image, nameLayout }
        };
        View = viewLayout;
    }//end constructor

    static StackLayout CreateLayout()
    {

        var titleLabel = new Label
        {
            HorizontalOptions= LayoutOptions.FillAndExpand,
            TextColor = Color.FromRgb(0, 110, 128)
        };
        titleLabel.SetBinding(Label.TextProperty, "Title");

        var detailLabel = new Label
        {
            HorizontalOptions = LayoutOptions.FillAndExpand
        };
        detailLabel.SetBinding(Label.TextProperty, "Detail");

        var layout = new StackLayout()
        {
            HorizontalOptions = LayoutOptions.StartAndExpand,
            Orientation = StackOrientation.Vertical,
            Children = { titleLabel, detailLabel }
        };
        return layout;
    }

}

But that won't load the even load the list a first time

I tried the Avrohom's code (found here Xamarin.Forms ListView OutOfMemoryError exception on Android), but unfortunately it still won't load the first time.

Does anyone have any ideas?

1条回答
2楼-- · 2019-06-12 08:18

Your images are probably way too big, not in the file-size sense, but the bitmap representation of those files.

You should use smaller images, or implement a custom cell renderer that does that for you at runtime. See the Xamarin article Load Large Bitmaps Efficiently.

查看更多
登录 后发表回答