Search code examples
c#silverlightimageimage-processingwriteablebitmap

Break image into tiles


Hey. I havea 480 x 800 image and would like to place this on my tilemap. I'm trying to split the image into into a grid (6 x 10) and assign each tile that specific portion of the image. Essentially, the tilemap will look like one big image since each tile has the relevant part of the image attached to it. What's the best way of doing this? I've tried going through each tile and drawing it to a WriteableBitmap, but all the images are the same.

WriteableBitmap wb = new WriteableBitmap(80,80);
Rect src= new Rect(x*Width,y*Height, 80, 80);
Rect dest= new Rect(0, 0, 80, 80);
wb.Blit(dest, mainWb, src); 
tile.SetImage(wb);

(x and y) are the just the indexes used when iterating through the tilemap, 80 is the tile height and width and mainWb is the big image I want to split. Thanks for any help.

edit: Full loop code:

    var mainImage = Application.GetResourceStream(new Uri("MainImage.jpg", UriKind.Relative)).Stream;
                    WriteableBitmap mainWb = new WriteableBitmap(480, 800);           

                    mainWb.SetSource(mainImage);
                    for (int x = 0; x < 6; x++)
                    {
                        for (int y = 0; y < 12; y++)
                        {
                            Tile tile = new Tile();

                            WriteableBitmap wb = new WriteableBitmap(80,80);


 Rect src = new Rect(x*Width,y*Height, 80, 80);

                        Rect dest = new Rect(0, 0, 80, 80);

                        wb.Blit(dest, mainWb, src); 
                        tile.SetImage(wb);    

                        Canvas.SetLeft(tile, x * WIDTH);
                        Canvas.SetTop(tile, y * HEIGHT);  


                        LayoutRoot.Children.Add(tile);
                        ls.Add(tile);
                    }
                }

The Tile class is a simple 80x80 canvas with an Image control called img. The SetImage method above is this:

 public void SetImage(WriteableBitmap wb)
        {                
            img.Source = wb;                     
        }

Solution

  • you can do it with a nice trick - just crop the image each time using a canvas, and move the image so each time another piece is showing:

            <Canvas Width="80" Height="80">
                <Canvas.Clip>
                    <RectangleGeometry Rect="0,0,80,80" />
                </Canvas.Clip>
                <Image Source="your_image.png" 
       Canvas.Left="0" Canvas.Top="0" />
                <!-- or -80, -160, -240 etc.. -->
            </Canvas>