Cutting an image into sections

Ok so I'm working on an app that takes an image and cuts it into 16 pieces for a small puzzle game. The problem is how to do this. The solution is GDI+ to the rescue! I found some help on MSDN to eventually get this code. My puzzle needs to be 16 pieces and each piece is a small section of a larger bitmap.


// get the piece width and height
pieceWidth = _originalImage.Width / 4;
pieceHeight = _originalImage.Height / 4;

// clear the existing puzzle
_puzzle.Clear();

for( int i = 0; i < 4; i++ )
{
for( int j = 0; j < 4; j++ )
{
Rectangle srcRect = new Rectangle( i * pieceWidth, j * pieceHeight, pieceWidth, pieceHeight );

// Create the new bitmap and associated graphics object
Bitmap bmp = new Bitmap( pieceWidth, pieceHeight );

Graphics g = Graphics.FromImage( bmp );

// Draw the specified section of the source bitmap to the new one
g.DrawImage( _originalImage, 0, 0, srcRect, GraphicsUnit.Pixel );


// Do something with the image we just saved in memory

// Clean up
g.Dispose();

}//end for j
}//end for i


This gets you 16 small section of the larger image

Comments

Popular Posts