I have "Out of memory" exception on windows phone when I try to display a grid of images.
I played with code a little and think that Grid.Children.Add
gives me that error.
I've made my custom class which shows gray rectangle and after an image was loaded, it shows the image instead of that rectangle. Here it is:
class ImageWIthLoader
{
private BitmapImage m_loader_bitmap;
private BitmapImage m_source_bitmap;
private Image m_image;
public Image image
{
get { return m_image; }
}
//url - url to 120x120 image; width, height = 120 both
public ImageWIthLoader(string url, int width, int height)
{
m_image = new Image();
m_loader_bitmap = new BitmapImage(new Uri("Assets/Images/image_await_background.png", Uri Kind.Relative));
m_loader_bitmap.DecodePixelWidth = width;
m_loader_bitmap.DecodePixelHeight = height;
m_image.Source = m_loader_bitmap;
m_source_bitmap = new BitmapImage(new Uri(url));
m_source_bitmap.CreateOptions = BitmapCreateOptions.None;
m_source_bitmap.ImageOpened += bitmapLoaded;
}
private void bitmapLoaded(object sender, RoutedEventArgs e)
{
m_image.Source = m_source_bitmap;
m_loader_bitmap.UriSource = null;
}
}
And in another class I add these images to the grid (it's a series of them, loaded by url from a previously parsed json)
private void addImageToGrid(ImageWIthLoader loader_image, int row, int col)
{
double margin = 0.05 * PIC_WIDTH;
loader_image.image.SetValue(Grid.ColumnProperty, col);
loader_image.image.SetValue(Grid.RowProperty, row);
loader_image.image.Margin = new Thickness(margin);
//comment out this string and everythins goes fine
images_grid.Children.Add(loader_image.image);
}
To guess some comments: I've made saving ImageWithLoader-s to List<> to prevent GC to collect them. ImageWithLoader url is an url of 120x120 images, so they must not be that heavy.
Part of XAML for the page with images grid:
....
<ScrollViewer x:Name="scrollView" HorizontalAlignment="Left" Height="603" VerticalAlignment="Top" Width="456" >
<Grid x:Name="images_grid" Height="596" Width="453"/>
</ScrollViewer>
....
So, please, what am I doing wrong? Should I use another control instead of grid? Or there is something else I am missing?
P.S. Sorry for misinform. The size 120x120 is the displayed rectangle, the images loaded have sizes 800x800 (for example) and after that they are fit into 120x120 rectangle.
P.P.S. If I remove loading m_loader_bitmap, then pictures are displayed fine. m_loader_bitmap is 1px gray png