简体   繁体   中英

How to use QImage repeatedly?

I have a horizontal sprite of images. This one for example:

在此处输入图片说明

All the images have the same width and height. I have stored it in my resources file, and declared it in my application by a define :

#define SPRITE QImage(":/sprite.png")

So there are 4 images that I will need several times in my application. In order to do this, I implemented this function which retrieves the image at the position n in the sprite.

QImage getNthImageFromSprite(int n, QImage sprite)
{
    int size = sprite.height();
    return sprite.copy((n - 1) * size, 0, size, size);
}

Then, I declared a general enum to put names on the position:

enum eImage
{
    eImage_black = 1,
    eImage_red,
    eImage_orange,
    eImage_green
}

And finally, the function that I'm using anywhere in my application:

QImage getSpriteImage(eImage img)
{
    return getNthImageFromSprite(img, SPRITE);
}

This works well .

But I have the impression that this is not very good, since I call the constructor of QImage each time I want to get a specific image. Knowing that a sprite can contain +40 images and that I will need these images several times, should I cache an image the first time it get called, or the way I'm doing it is good?


Note: I need QImage for various reasons, but a comparison with QPixmap would be appreciated.

Replace the define with an object:

static QImage SPRITE(":/sprite.png");

It will be initialized only once on startup.

You can even put it in the method:

QImage getSpriteImage(eImage img)
{
    static QImage SPRITE(":/sprite.png");
    return getNthImageFromSprite(img, SPRITE);
}

In this case, it is initialized on first usage.

Howerver, you sill create new objects for every call to getNthSpriteImage . You could use a local static cache to re-use already returned objects:

QImage getNthSpriteImage(int n, QImage img) {
    static QMap<int, QImage> cache;
    if (!cache.contains(n)) {
        int size = sprite.height();
        cache[n] = sprite.copy((n - 1) * size, 0, size, size);
    }
    return cache[n];
}

As for the difference for QImage/QPixmap, this is the main difference:

QImage is designed and optimized for I/O, and for direct pixel access and manipulation, while QPixmap is designed and optimized for showing images on screen.

So I would recommend to use QPixmap if you don't want special image formats (RGBA, premultiplied RGBA, indexed, ...) or use direct pixel manipulation.

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