2010-08-01 52 views
2

我試圖從WPF邊框生成一個位圖。整個事情在一個asp.net應用程序(當然是服務器端)運行.net 4.0。在ASP.NET中生成WPF UIElement的位圖

問題是,生成的圖像是空的。有沒有人有一個想法,爲什麼?

這是代碼。

public static byte[] Draw(int width, int height) 
    { 
     MemoryStream memoryStream 
      = new MemoryStream(); 
     Thread t = new Thread(delegate() 
      { 
       System.Windows.Controls.Border border = new System.Windows.Controls.Border() 
       { 
        Background = Brushes.Red, 
        BorderBrush = Brushes.Green, 
        CornerRadius = new System.Windows.CornerRadius(5), 
        Width = width, 
        Height = height 
       }; 

       border.ApplyTemplate(); 

       RenderTargetBitmap renderTargetBitmap = 
        new RenderTargetBitmap(width, height, 90, 90, PixelFormats.Pbgra32); 

       renderTargetBitmap.Render(border); 

       BitmapEncoder bitmapEncoder = 
        new PngBitmapEncoder(); 

       bitmapEncoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap)); 
       bitmapEncoder.Save(memoryStream); 
      }); 
     t.SetApartmentState(ApartmentState.STA); 
     t.Start(); 
     bool success = t.Join(5000); 

     if (success) 
      return memoryStream.ToArray(); 
     else 
      throw new Exception("Fail"); 
    } 

的結果是相當糟糕的,正如我所說的東西返回用正確的寬度和高度的圖像,但它是空的,所以我想我不亂的事情了和穿線位。

回答

4

border.ApplyTemplate之後添加:你是在保存前

border.Measure(new Size(width, height)); 
border.Arrange(new Rect(0, 0, width, height)); 
border.UpdateLayout(); 

你的邊界沒有更新自己。

+0

不錯,謝謝隊友! – 2010-08-01 14:42:33