Take the 2-minute tour ×

I'm creating a level editor in WPF for a 2D tile-based game. I'm trying to figure out the best way to load the tileset Image file and render each tile in the appropriate location to reconstruct the map.

Currently, I'm loading the Image as a BitmapSource, and I'm deriving from the Canvas class for the control that displays the map. I'm overriding the OnRender method so I can get a DrawingContext. However, DrawingContext.DrawImage doesn't appear to have an appropriate overload that draws only a subrect of an image; it looks like I have to draw the entire image.

What should I use if I want to draw subrects of an Image onto a Canvas? Or should I be using something other than a Canvas?

share|improve this question
add comment

1 Answer

Here is how I would do it:

protected override void OnRender(DrawingContext dc)
	BitmapImage source = new BitmapImage();
	source.UriSource = new Uri(@"pack://application:,,,/YourProject;component/YourImage.jpg");
	source.SourceRect = new Int32Rect(0, 0, 200, 200);

	dc.DrawImage(source, Rect.Parse("0, 0, 200, 200"));

The property that does this for you is BitmapImage.SourceRect.

share|improve this answer
add comment

Your Answer


