2009-03-08 31 views
5

Lớp System.Windows.Forms.Control của Winforms có một phương thức thể hiện "DrawToBitmap" mà tôi nghĩ là rất hữu ích trong nhiều trường hợp khác nhau. Tôi tự hỏi nếu có một cách tương đương để nhận được một System.Drawing.Bitmap từ một ứng dụng WPF?Nhận bitmap từ cửa sổ ứng dụng WPF?

Tôi nhận ra mình có thể thực hiện một số công cụ P/Invoke để có cửa sổ ứng dụng, tuy nhiên tôi không thích điều này vì nó không chứa chuyển đổi 64 bit rất tốt và không cho phép tôi hiển thị các điều khiển phụ chỉ, như DrawToBitmap.

Cảm ơn, Richard

Trả lời

9

Sử dụng RenderTargetBitmap như trên MSDN

RenderTargetBitmap bitmap = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32); 
bitmap.Render(this.YourVisualControlNameGoesHere); 
2

TFD là tại chỗ trên. Bạn cũng có thể sử dụng ví dụ tham khảo ít thanh lịch hơn từ MSDN:

Dim width As Integer = 128 
Dim height As Integer = width 
Dim stride As Integer = CType(width/8, Integer) 
Dim pixels(height * stride) As Byte 

' Try creating a new image with a custom palette. 
Dim colors As New List(Of System.Windows.Media.Color)() 
colors.Add(System.Windows.Media.Colors.Red) 
colors.Add(System.Windows.Media.Colors.Blue) 
colors.Add(System.Windows.Media.Colors.Green) 
Dim myPalette As New BitmapPalette(Colors) 

' Creates a new empty image with the pre-defined palette 
Dim image As BitmapSource = System.Windows.Media.Imaging.BitmapSource.Create(width, height, 96, 96, PixelFormats.Indexed1, myPalette, pixels, stride) 
Dim stream As New FileStream("new.bmp", FileMode.Create) 
Dim encoder As New BmpBitmapEncoder() 
Dim myTextBlock As New TextBlock() 
myTextBlock.Text = "Codec Author is: " + encoder.CodecInfo.Author.ToString() 
encoder.Frames.Add(BitmapFrame.Create(image)) 
encoder.Save(stream) 
Các vấn đề liên quan