Using user specified or random image
[impuzzle] / src / imageimporter.cpp
1 /*
2   Image Puzzle - A set your pieces straight game
3   Copyright (C) 2009  Timo Härkönen
4
5   This program is free software: you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published by
7   the Free Software Foundation, either version 3 of the License, or
8   (at your option) any later version.
9
10   This program is distributed in the hope that it will be useful,
11   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   GNU General Public License for more details.
14
15   You should have received a copy of the GNU General Public License
16   along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18
19 #include "imageimporter.h"
20 #include "puzzleitem.h"
21 #include "defines.h"
22
23 #include <QPixmap>
24
25 #include <QDebug>
26
27 ImageImporter *ImageImporter::instance_ = 0;
28
29 ImageImporter::ImageImporter(QObject *parent) :
30         QObject(parent)
31 {
32
33 }
34
35 ImageImporter *ImageImporter::instance()
36 {
37     if(!instance_) {
38         instance_ = new ImageImporter;
39     }
40
41     return instance_;
42 }
43
44 QList<PuzzleItem *> ImageImporter::newPieces(const QPixmap &pixmap, const int count)
45 {
46     QPixmap tmp;
47
48     if(pixmap.isNull()) {
49         qDebug() << "Got NULL image - using default.jpg";
50         tmp = QPixmap(":/images/default.jpg");
51     }
52     else {
53         tmp = pixmap;
54     }
55
56     if(tmp.size().height() != IMAGE_HEIGHT || tmp.size().width() != IMAGE_WIDTH) {
57         tmp = pixmap.scaled(QSize(IMAGE_WIDTH, IMAGE_HEIGHT), Qt::KeepAspectRatioByExpanding);
58     }
59
60     QList<PuzzleItem *> list;
61
62     int horizontalCount = 0;
63
64     if(count == 12) {
65         horizontalCount = 4;
66     }
67     else if(count == 20) {
68         horizontalCount = 5;
69     }
70     else {
71         return list;
72     }
73
74     int verticalCount = count / horizontalCount;
75     int verticalStep = IMAGE_HEIGHT / verticalCount;
76     int horizontalStep = IMAGE_WIDTH / horizontalCount;
77
78     for(int i = 0; i < verticalCount; ++i) {
79         for(int j = 0; j < horizontalCount; ++j) {
80             PuzzleItem *item = new PuzzleItem;
81             item->setPixmap(tmp.copy(QRect(QPoint(j * horizontalStep, i * verticalStep),
82                                            QPoint(horizontalStep + j * horizontalStep, verticalStep + i * verticalStep))));
83             list.append(item);
84         }
85     }
86
87     return list;
88 }