Reputation:
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
?
Upvotes: 0
Views: 1795
Reputation: 15247
Here is how I would do it:
protected override void OnRender(DrawingContext dc)
{
BitmapImage source = new BitmapImage();
source.BeginInit();
source.UriSource = new Uri(@"pack://application:,,,/YourProject;component/YourImage.jpg");
source.SourceRect = new Int32Rect(0, 0, 200, 200);
source.EndInit();
dc.DrawImage(source, Rect.Parse("0, 0, 200, 200"));
base.OnRender(dc);
}
The property that does this for you is BitmapImage.SourceRect.
Upvotes: 1