由于WriteableBitmap,WP8(C#和Silverlight)上的OutOfMemoryException

时间:2013-11-07 03:08:35

标签: c# silverlight windows-phone writablebitmap

我正在创建和应用,需要向UIElement添加和删除大量Canvas。 基本上Canvas包含UIElement的集合,并根据其包含的内容在屏幕上自动呈现/更新它。

为了避免屏幕上有大量UIElements人互相重叠,我宁愿在辅助Canvas上添加所有这些内容,然后从中创建Image(谢谢到WritableBitmap)。最后,我在当前Image上添加了此Canvas。 通过允许我的画布上只有少量图像,我希望有更好的性能。 不幸的是,我似乎无法完全删除WritableBitmap,即使我将其设置为null

以下代码说明了这一点:

//My constructor
public  WP8Graphics() 
{
    //Here my collection DataBinded with the Canvas from the Mainpage
    this.UIElements = new ObservableCollection<UIElement>();
    //The secondary Canvas
    GraphicCanvas = new Canvas();
    GraphicCanvas.Height = MainPage.CurrentCanvasHeight;
    GraphicCanvas.Width = MainPage.CurrentCanvasWidth;
}


///This method can be hit thousand times, it basically create a rectangle 
public void fillRect(int x, int y, int width, int height)
{

// some code
// CREATE THE RECTANGLE rect

   GraphicCanvas.Children.Add(rect); // My secondary Canvas



   WriteableBitmap wb1 = new WriteableBitmap(GraphicCanvas, null);
   wb1.Invalidate();

   WriteableBitmap wb2 = new WriteableBitmap((int)MainPage.CurrentCanvasWidth, (int)MainPage.CurrentCanvasHeight);

  for (int i = 0; i < wb2.Pixels.Length; i++)
  {
       wb2.Pixels[i] = wb1.Pixels[i];
  }
  wb2.Invalidate();

  wb1 = null;

  Image thumbnail = new Image();
  thumbnail.Height = MainPage.CurrentCanvasHeight;
  thumbnail.Width = MainPage.CurrentCanvasWidth;
  thumbnail.Source = wb2;



  this.UIElements.Add(thumbnail);

}

在24 WriteableBitmap之后,会出现 OutOfMemoryException 。 我阅读了很多关于这个问题的文章,在我的例子中,似乎WriteableBitmap依赖于我的 GraphicCanvas 而仍然是因为它仍然有引用它。我无法删除我的Graphic Canvas,也无法将 myImage 源设置为null。

我有两个问题:

  • 是否有其他方法可以从Canvas或UIElements集合创建图像?
  • 是否可以删除保持WriteableBitmap活着的引用?

我希望足够清晰易读。

感谢您的阅读。

用atomaras建议编辑,但仍然是同样的问题

WriteableBitmap wb1 = new WriteableBitmap(GraphicCanvas, null); 该行仍然抛出OutOfMemoryException。

1 个答案:

答案 0 :(得分:1)

您需要将原始writeablebitmap(将保留在GraphicsCanvas上)的像素复制到新的writeablebitmap。

看一下这篇精彩的帖子http://www.wintellect.com/blogs/jprosise/silverlight-s-big-image-problem-and-what-you-can-do-about-it

另外,为什么要将所有可写的比特图保留在UIElements集合中?最新的那个不够吗?你不能在添加最新的/新的位图之前清除UIElements集合吗?