简体   繁体   中英

How to split a random image into 9 equal parts for puzzle game

I am trying to split an image into 9 equal parts. Like we see in a puzzle game. Image can be any random image. I am trying some code but it is not splitting it into equal parts - it needs coordinate values for rectangles, but I need simple general code to split an image into equal parts.

I've an image. I want to crop it or split into 9 equal parts. But the below code just crops the same part of the image from the right top corner every time.

var imgarray = new Image[9];
var img = Image.FromFile("media\\a.png");
for (int i = 0; i < 3; i++)
{
    for (int j = 0; j < 3; j++)
    {
var index = i * 3 + j;
        imgarray[index] = new Bitmap(104, 104);
        var graphics = Graphics.FromImage(imgarray[index]);
        graphics.DrawImage(img, new Rectangle(0, 0, 104, 104), new Rectangle(i * 104, j * 104, 104, 104), GraphicsUnit.Pixel);
        graphics.Dispose();
    }
}

Some other tidy ups...

var imgarray = new Image[9];
var img = Image.FromFile("media\\a.png");
for (int i = 0; i < 9; i++)
{
        imgarray[i] = new Bitmap(104, 104);
        var graphics = Graphics.FromImage(imgarray[i]);
        graphics.DrawImage (
             img, 
             new Rectangle(0, 0, 104, 104),
             new Rectangle( (i%3) * 104, (i/3) * 104, 104, 104),
             GraphicsUnit.Pixel);
        graphics.Dispose();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM