Using canvas to draw image sometimes has mosaics

Description

I use canvas to draw different images. These images use lv_lodepng decode.
For example:

void Image::DrawImage(const std::string& src, double factor, int width, int height)
{
    lv_draw_img_dsc_t dsc;
    lv_draw_img_dsc_init(&dsc);
    dsc.zoom = factor * LV_IMG_ZOOM_NONE;

    /*canvas will be created when canvas is not exist*/
    CreateCanvas();
    
    auto bufSize = LV_CANVAS_BUF_SIZE_TRUE_COLOR_ALPHA(width, height);
    if (/*canvas buffer member variable*/_canvasBuf.size() < bufSize)
    {
        _canvasBuf.resize(bufSize);
        lv_canvas_set_buffer(_canvas, _canvasBuf.data(), width, height, LV_IMG_CF_TRUE_COLOR_ALPHA);
    }
    memset(_canvasBuf.data(), 0, _canvasBuf.size());
    lv_canvas_draw_img(/*canvas member variable*/_canvas, 0, 0, src.data(), &dsc);
}

If I set the LV_IMG_CACHE_DEF_SIZE to 30, canvas sometimes has mosaics.
For example:

But if set the LV_IMG_CACHE_DEF_SIZE to 1, It won’t.

Version

V7.1.0

It looks like you’re getting the image data from src. Is that staying in scope, or being freed after this function exits? When you increase the image cache, LVGL can refer to the same region of memory later on to redraw the image.

I use image file. I didn’t release the memory manually.
The canvas buffer is a member variable, I will resize it when not enough space.
There is a problem: different images may use the same block of image cache.

You should call lv_img_cache_invalidate_src(_canvasBuf.data()) if you change the image on the fly.

Thanks. I use lv_img to resolve this problem.