Thursday, January 13, 2011

QRect.setX() and QRect.setY() are evil!

I tried to tile an image using this algorythm:

 bool copyTileContainerFromImageFile( QString &fileString, QVector<Tile*> *sourceVector )  
{
if(fileString.isEmpty())
return false;
QRect rect(0,0,32,32);
QPixmap originalImage(fileString);
//goal = amount of possible tiles in this image.
int goal = (originalImage.width() * originalImage.height()) / 1024; //1024 Pixels fits in one Tile
sourceVector->reserve(goal); //reserves the amount of images in the vector.
for(int i = 0;i != goal;i++) {
sourceVector->append(new Tile(rect,i,originalImage.copy(rect)));
if(rect.x() + 32 >= originalImage.width()) {
rect.setY(32 + rect.y());
rect.setX(0);
}else
rect.setX(32 + rect.x());
}
return true;
}


the result using this algorythm was this:



If you're now like "WTF?" then I can tell you that "WTF?" was my first reaction,too.
I really had no freakin' idea why the image got tiled like THAT.

After I posted in some forums and read through the documentantion I changed
the algorythm to this:
 bool copyTileContainerFromImageFile( QString &fileString, QVector<Tile*> *sourceVector )  
{
if(fileString.isEmpty())
return false;
QRect rect(0,0,32,32);
QPixmap originalImage(fileString);
//goal = amount of possible tiles in this image.
int goal = (originalImage.width() * originalImage.height()) / 1024; //1024 Pixels fits in one Tile
sourceVector->reserve(goal); //reserves the amount of images in the vector.
for(int i = 0;i != goal;i++) {
sourceVector->append(new Tile(rect,i,originalImage.copy(rect)));
if(rect.x() + 32 >= originalImage.width()) {
rect.moveTop(32 + rect.y()); <--was setY(32 + rect.y()) before
rect.moveLeft(0); <--was setX(0) before
}else
rect.moveLeft(32 + rect.x()); <--was setX(32 + rect.x()) before
}
return true;
}

Now everything works fine.

EDIT:
Nice tool for everyone who's posting sourcecode in blogspot posts:
Code formatter

No comments:

Post a Comment