通用库将控件呈现到位图

时间:2013-07-16 20:12:10

标签: bitmap shared-libraries windows-phone

我正在寻找一个通用的Nuget包/库来将用户控件呈现为位图。我可以使用已知的用户控件来完成这项工作,包括等待任何Image控件加载其源代码,但这并不像通用解决方案那样容易(传递一个Control,返回位图)。我希望Measure / Arrange调用与SizeChanged / Loaded / LayoutUpdated事件相结合可以帮助我知道什么时候一切都准备就绪,但事件没有在我期望的时候加载。有没有我不知道的解决方案,或者某种方式更好地连接事件?

1 个答案:

答案 0 :(得分:2)

您可以在页面上触发Loaded事件后将任何控件呈现为位图。例如,下面的代码应该将LayoutRoot和ContentPanel渲染为位图,然后将它们保存为手机图片库中的jpgs。

public MainPage() {
  InitializeComponent();

  Loaded += (s, e) => {
    SaveToMediaLibrary(GetBitmap(LayoutRoot), "LayoutRoot.jpg", 100);
    SaveToMediaLibrary(GetBitmap(ContentPanel), "ContentPanel.jpg", 100);
  };
}

private WriteableBitmap GetBitmap(FrameworkElement fe) {
  // This will make sure all content are sized properly before returning
  //fe.UpdateLayout();

  var bmp = new WriteableBitmap((int)fe.ActualWidth, (int)fe.ActualHeight);
  bmp.Render(fe, new MatrixTransform());         
  bmp.Invalidate();
  return bmp; 
}       

public void SaveToMediaLibrary(WriteableBitmap bitmap, string name, int quality) {   
  using (var stream = new MemoryStream())            {         
    // Save the picture to the Windows Phone media library.             
    bitmap.SaveJpeg(stream, bitmap.PixelWidth, bitmap.PixelHeight, 0, quality);   
    stream.Seek(0, SeekOrigin.Begin);            
    new MediaLibrary().SavePicture(name, stream);        
  }     
}