2012-07-24 30 views

回答

4

加載您的XAML文件:

Stream s = File.OpenRead("yourfile.xaml"); 
Control control = (Control)XamlReader.Load(s); 

和創建的BitmapImage:

public static void SaveImage(Control control, string path) 
    { 
     using (MemoryStream stream = new MemoryStream()) 
     { 
      GenerateImage(element, stream); 
      Image img = Image.FromStream(stream); 
      img.Save(path); 
     } 
    } 

    public static void GenerateImage(Control control, Stream result) 
    { 
     //Set background to white 
     control.Background = Brushes.White; 

     Size controlSize = RetrieveDesiredSize(control); 
     Rect rect = new Rect(0, 0, controlSize.Width, controlSize.Height); 

     RenderTargetBitmap rtb = new RenderTargetBitmap((int)controlSize.Width, (int)controlSize.Height, IMAGE_DPI, IMAGE_DPI, PixelFormats.Pbgra32); 

     control.Arrange(rect); 
     rtb.Render(control); 

     PngBitmapEncoder png = new PngBitmapEncoder(); 
     png.Frames.Add(BitmapFrame.Create(rtb)); 
     png.Save(result); 
    } 

    private static Size RetrieveDesiredSize(Control control) 
    { 
     control.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); 
     return control.DesiredSize; 
    } 

確保包括正確的庫!這些課程位於System.Windows.Media

希望這會有所幫助!

+0

感謝您的快速響應。 – anton 2012-07-25 05:35:17

+0

只做了一個小小的編輯:將SaveImage方法中的**元素** var重命名爲** control **。 – anton 2012-07-25 07:04:52

+0

幾個問題: 1.如何控制輸出位圖的分辨率? 2.我如何知道使用哪個DPI? – anton 2012-07-25 08:11:46