Cutting image files to separate QPixmaps
This code snippet shows how you can load an image file (for example, PNG) and separate it into several smaller QPixmap tiles for display. This is useful, for example, if you wanted to implement a slide puzzle game.
Article Metadata
Source code
QList<QPixmap*> frames; //will include the output frames
QString file = "c:/image.png";
int cols = 5;
int rows = 5;
QPixmap *image = new QPixmap(file);
if (cols == 1 && rows == 1) {
frames.append(image);
w = image->width();
h = image->height();
}
else {
int iw = image->width();
int ih = image->height();
w = iw/cols;
h = ih/rows;
int x = 0;
int y = 0;
for (int r=0; r < rows; r++) {
for (int c=0; c < cols; c++) {
QPixmap *cropped = new QPixmap(image->copy(x,y,w,h));
frames.append(cropped);
x += w;
}
y += h;
x = 0;
}
delete image;
}
//Do something with the pixmaps
//Delete in the end
if (frames.count() > 0) {
foreach (QPixmap* pixmap, frames) {
delete pixmap;
}
}
frames.clear();

