efficient canvas refresh with fyne golang

1.8k Views Asked by At

I have the code below, It shows a window, generate an image as raster and then update the window content with it. However, the setContent method is slow (with it I have 100% of 1 cpu core and almost 0 without).

I wonder if there is anything to do to do what I do here efficiently (modifiying underlaying raster, use gpu in anyway...) . I would like to be able to generate an image with raster and then display it at ~60 fps efficiently.

Any suggestion or other tools to do it better would be appreciated.

package main

import (
    "image/color"
    "math/rand"
    "time"

    "fyne.io/fyne/v2/app"
    "fyne.io/fyne/v2/canvas"
)

func main() {
    myApp := app.New()
    w := myApp.NewWindow("Raster")

    go func() {
        for {
            time.Sleep(time.Millisecond * 500)
            raster := canvas.NewRasterWithPixels(
                func(_, _, w, h int) color.Color {
                    return color.RGBA{uint8(rand.Intn(255)),
                        uint8(rand.Intn(255)),
                        uint8(rand.Intn(255)), 0xff}
                })
            w.SetContent(raster)
        }
    }()
    w.SetFullScreen(true)
    // w.Resize(fyne.NewSize(120, 100))
    w.ShowAndRun()
}
1

There are 1 best solutions below

0
On

Setting the window content is a very expensive call as it has to re-layout all the content and check sizes etc. Just call raster.Refresh() instead. You could also cache the raster pixels in your widget so you don’t have to create a new image for every frame to refresh.