Raster

The canvas.Raster is like an image but draws exactly one spot for each pixel on the screen. This means that as a user interface scales or the image resizes more pixels will be requested to fill the space. To do this we use a Generator function as illustrated in this example - it will be used to return the colour of each pixel.

The generator functions can be pixel based (as in this example where we generate a new random colour for each pixel) or based on full images. Generating complete images (with canvas.NewRaster() is more efficient but sometimes controlling pixels directly is more convenient.

If your pixel data is stored in an image you can load it through the NewRasterFromImage() function which will load the image to display pixel perfect on screen.

Example Code

            
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package main

import (
	"fyne.io/fyne"
	"fyne.io/fyne/app"
	"fyne.io/fyne/canvas"
	"image/color"
	"math/rand"
)

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

	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}
		})
	// raster := canvas.NewRasterFromImage()
	w.SetContent(raster)
	w.Resize(fyne.NewSize(120, 100))
	w.ShowAndRun()
}