2017-03-03 66 views
0

我不知道我是否在問正確的問題;所以提前道歉。我正在將一些PNG寫入畫布,我也想同時將PNG複製到位圖。我希望PNG出現在位圖上與在畫布上相同的位置上。如何將圖像轉換爲ImageSource

這是代碼片段:

WorkingBMP = new RenderTargetBitmap(BOARD_WIDTH, BOARD_HEIGHT, 96, 96, PixelFormats.Pbgra32); 

TreeFile = "pack://application:,,,/Images/" + TreeFile; 

var image = new Image 
{ 
    Source = new BitmapImage(new Uri(TreeFile)) 
}; 
image.Width = 10; 
image.Height = 10; 

Canvas.SetLeft(image, x); 
Canvas.SetTop(image, y); 

DrawingVisual drawingVisual = new DrawingVisual(); 
DrawingContext drawingContext = drawingVisual.RenderOpen(); 
drawingContext.DrawImage(image, new Rect(x, y, image.Width, image.Height)); 
drawingContext.Close(); 

WorkingBMP.Render(drawingVisual); 

MainCanvas.Children.Add(image); 

然而,它拋出錯誤「無法從‘System.Windows.Controls.Image’對這一行‘System.Windows.Media.ImageSource’轉換:

drawingContext.DrawImage(image, 
        new Rect(x, y, image.Width, image.Height)); 

請問,如果我能以某種方式轉換圖像到一個ImageSource的還是我這一切錯這個錯誤得到解決?

謝謝!

+1

在上面的代碼,您_create_ a ['BitmapImage'](https://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapimage(v = vs.110).aspx)object,wh ich是一個'ImageSource'(標準的OOP/Liskov替換/等等)。你爲什麼不使用這個對象?你爲什麼試圖將WPF UI元素轉換爲不是? –

回答

1

如果BitmapImage的直接繪製,它應該工作

var source = new BitmapImage(new Uri(TreeFile)) 

drawingContext.DrawImage(source, 
        new Rect(x, y, image.Width, image.Height)); 
+0

謝謝!非常感激! – zetar

0

Image是窗口上的控件。 Image.Source是實際位圖Image檢索以進行呈現。它可能並不明顯,但您的代碼對此有點暗示,因爲您將Source設置爲BitmapImage

您需要使用source屬性才能獲得實例化的實際BitmapImage

您可能需要轉換,但這應該工作:

drawingContext.DrawImage(image.Source, 
        new Rect(x, y, image.Width, image.Height)); 
+0

感謝您解釋這一點! – zetar

-1

這裏試試這個

WorkingBMP = new RenderTargetBitmap(BOARD_WIDTH, BOARD_HEIGHT, 96, 96, PixelFormats.Pbgra32); 

TreeFile = "pack://application:,,,/Images/" + TreeFile; 

var image = new Image 
{ 
    Source = new BitmapImage(new Uri(TreeFile)) 
}; 
image.Width = 10; 
image.Height = 10; 

Canvas.SetLeft(image, x); 
Canvas.SetTop(image, y); 

DrawingVisual drawingVisual = new DrawingVisual(); 
DrawingContext drawingContext = drawingVisual.RenderOpen(); 
drawingContext.DrawImage(new BitmapImage(new Uri(TreeFile)), new Rect(x, y, image.Width, image.Height)); 
drawingContext.Close(); 

WorkingBMP.Render(drawingVisual); 

MainCanvas.Children.Add(image); 
+0

謝謝!似乎工作! – zetar