Skip to main content

Canvas Widgets

Canvas Widgets and the Canvas Widget Renderer are a powerful and versatile add-on to TouchGFX which provides nice smooth, anti-aliased drawing of geometric shapes using relatively little memory while maintaining high performance. However, rendering geometrical shapes must be seen as a quite expensive operation and can easily strain the microcontrollers resources if not used carefully.

The Canvas Widget Renderer (hereafter referred to as CWR) is a general graphics API, providing optimized drawing for primitives, automatically eliminating most superfluous drawings. CWR is used by TouchGFX for drawing complex geometric shapes. Geometric shapes are defined by Canvas Widgets. TouchGFX comes with a number of supported Canvas Widgets but just like normal widgets you can make your own custom Canvas Widget to match your needs. Where a Canvas Widget defines the geometric shape of a figure to be drawn by the CWR, the actual color of each pixel inside the figure is defined by an associated Painter class. Again, TouchGFX comes with a number of Painters but you can make your own custom Painters to match your needs.

Using CanvasWidgets

Other widgets in TouchGFX have their sizes set automatically. A bitmap widget, for example, will automatically get the width and height of the contained bitmap. It is therefore enough to use setXY() on the bitmap widget to place the bitmap on the display.

Canvas Widgets do not have a default size which can be determined automatically and set initially. Care must be taken to not only position, but also size the widget correctly, otherwise the width and height of the Canvas Widget will be zero, and nothing will be drawn on the display.

So, instead of using setXY(), use setPosition() to place and size the canvas widget. See also Custom Canvas Widgets below for an example on how to create and use a custom canvas widget.

Once the position and size of the Canvas Widget has been set, a geometrical shape can be drawn inside it. The coordinate system will have (0, 0) in the upper left corner of the widget (not the display), the X axis stretches to the right and the Y axis stretches downwards.

Canvas widgets are also supported in TouchGFX Designer, and make the usage simple and has automatic memory requirement calculation and automatic memory allocation.

Available CanvasWidget based widgets in TouchGFX Designer:

Using these widgets via TouchGFX Designer, makes placement and size adjustment much easier by showing how the widget will look at run time.

Memory Allocation and Usage

To produce nice anti-aliased complex geometrical shapes additional memory is required. For this CWR has to have a special allocated memory buffer that is used during rendering. CWR, as the rest of TouchGFX, has no dynamic memory allocation.

Memory Allocation in TouchGFX Designer

When adding a widget to the canvas of a Screen, a memory buffer is automatically generated. The size of the buffer is based upon the width of the Screen with the following formula (Width × 3) × 5. This is however not always the ideal buffer size for all scenarios. Therefore the buffer size can be overridden has shown in the image below.

Canvas buffer size being overridden in Screen properties

Memory Allocation in User Code

The memory buffer can be allocated and set up in target/main.cpp and simulator/main.cpp or be setup and allocated per Screen.

static const uint16_t CANVAS_BUFFER_SIZE = 3600;
static uint8_t canvasBuffer[CANVAS_BUFFER_SIZE]

A static const defining the size of the memory buffer, and the actual memory buffer can be defined in the beginning of the main.cpp or ScreenView.hpp

Then in either the main() method of main.cpp or setupScreen() method of ScreenView.cpp the following line setting up the buffer can be added.

CanvasWidgetRenderer::setupBuffer(canvasBuffer, CANVAS_BUFFER_SIZE);

The amount of CWR memory needed depends on the maximum size of the shapes that are to be drawn in the application. You can, however, reserve less memory than required by the most complex shape. To handle this situation, the CWR splits the drawing of shapes into smaller frame buffer parts resulting in slightly longer rendering time, as shapes in these cases will sometimes have to be rendered more than once. It is possible to investigate the memory consumption closer and fine-tune it when running in simulator mode. Simply add the following function call to your main.cpp:

CanvasWidgetRenderer::setWriteMemoryUsageReport(true);

Now whenever a draw operation finishes, CWR will report (print in the console) how much memory was required. For canvas_widget_example this could be “CWR requires 3604 bytes” (for the first draw operation) followed by “CWR requires 7932 bytes (4328 bytes missing)” (for the second draw operation). Even though it appears that CWR does not have enough memory (4328 bytes missing in this case) the application runs fine. This is because CWR detects that too little memory is available to complete the complex draw operation in a single run. Instead, it splits the draw operation into two separate draw operations and the shape will be drawn just fine but will require more time to render.

Setting the correct memory buffer size is therefore a trade off between memory and performance (rendering time). A good starting value is usually around 3000, but using the above technique, a better value can often be determined. If the shape is too complex and the allocated memory buffer is too small, part of the shape will not be drawn (some vertical pixel lines will be skipped) and it is possible that nothing is drawn at all. In any case rendering time will increase a lot.

This means that if you want your application to render the CWR drawing at maximum speed you need to allocate the requested amount of memory. But if you can go with a slower rendering timer it is perfectly okay to reduce the memory buffer.

The CWR Coordinate System

The coordinate system in TouchGFX is normally used to address pixels for positioning bitmaps on the display. Bitmaps, texts and other graphic elements are all placed in a coordinate system, where (0,0) is the upper left hand pixel, the x-axis extends to the right and the y-axis extends downwards. In CWR it is not enough to be able to address pixels using integers, though this might be enough in special cases, this is far from enough in general. To demonstrate this, consider a circle with line width 1, which must fit precisely inside a box of 5 by 5 pixels. The center of this circle must be at (2.5, 2.5) and the radius must be 2, so fractions are required for the center coordinate. Similarly, if the circle should fit inside a box of 6 by 6 pixels, the center must be at (3, 3) and the radius must be 2.5, so here fractions are required for the radius.

This new way of addressing coordinates for drawing graphics, means that the center of the pixel at (0,0) has CWR coordinate (0.5, 0.5). Hence, the box containing the pixel in the upper left corner of the screen has the following outline: (0,0) -> (1,0) -> (1,1) -> (0,1) -> (0,0).

CWR coordinate system for pixel at (0,0)

Though this might seem confusing at first, it quickly becomes very natural. Where the coordinate system for bitmaps address the pixels, the same coordinate for Canvas Widgets address the gap just before and above the pixel.

Since circles are shapes that often will have to moved half a pixel to place the center correctly, the function Circle::setPixelCenter() will place the circle center at the center of the given pixel, i.e. half a pixel further to the right and down, compared to the coordinates specified.

Custom Canvas Widgets

Implementing a custom Canvas Widget requires an implementation of a new class with the following functions:

virtual bool drawCanvasWidget(const Rect& invalidatedArea) const;
virtual Rect getMinimalRect() const;

The drawCanvasWidget() must draw whatever the custom widget needs to draw and getMinimalRect() should return the actual rectangle in the Widget which contains the geometrical shape.

Note
The reason for having getMinimalRect() is that a geometrical shape can be moved around inside its widget and it is often impractical to resize and reposition the widget whenever the shape changes to only invalidate the smallest possible area.

A dummy implementation of getMinimalRect() could simply return rect;, that is the size of the widget, but that would cause the entire area covered by the canvas widget to be redrawn, and not just the part of the canvas widget containing the geometrical shape. Very often, the geometrical shape occupies only a small part of the canvas widget.

Canvas Widgets all use the Canvas class, which encapsulates the Canvas Widget Renderer as described above. CWR has many optimizations applied automatically, though awareness of your geometrical shape in relation to the invalidated area, and avoiding unnecessary drawing outside the invalidated area, is always a good way to boost performance.

A rough implementation of a diamond shaped square inside a 10x10 box could look something like this:

class Diamond10x10 : public CanvasWidget
{
public:
virtual Rect getMinimalRect() const
{
return Rect(0,0,10,10);
}
virtual bool drawCanvasWidget(const Rect& invalidatedArea) const
{
Canvas canvas(this, invalidatedArea);
canvas.moveTo(5,0);
canvas.lineTo(10,5);
canvas.lineTo(5,10);
canvas.lineTo(0,5);
return canvas.render(); // Shape is automatically closed
}
};
Note
Again, be careful that getMinimalRect() returns to correct rectangle, or the graphics on screen might be wrong.

In order to see the Diamond10x10 on the display, the color must be set using Diamond10x10::setPainter() inherited from CanvasWidget. Also, the Diamond10x10 must be placed and sized correctly. This could look similar to this:

In the header file declare

Diamond10x10 box;
PainterRGB565 myPainter;

and in the code you should have something like this:

myPainter.setColor(Color::getColorFromRGB(0xFF, 0x0, 0x0));
box.setPosition(100,100,10,10);
box.setPainter(myPainter);
add(box);

Painters (#painters)

A Painter defines a coloring scheme to fill a Canvas Widget object, thus painters are needed to make shapes visible. A painter can supply a single color for all pixels, e.g. PainterRGB565, or copy each pixel from a supplied bitmap, e.g. PainterRGB565Bitmap. Since a painter writes the pixels directly to the framebuffer, the selected painter must match the specifications of the target display or dynamic bitmap. TouchGFX comes with painters for all supported displays with painters specific for a solid color, or drawing a bitmap.

Painters that draw pixels from a bitmap, can also draw the bitmap tiled, which can help reduce the memory requirement.

Custom Painters

Even though TouchGFX comes with a set of predefined painter classes covering most usecase scenarios, custom painters can also be implemented.

In order to implement a custom Painter, care must be taken to never write outside the frame buffer (this isi handled by the abstract painter base classes). Here is an example of a custom Painter which we will use to paint an object red, only function renderNext() needs to be implemented. See AbstractPainter for more information.

class RedPainter : public AbstractPainterRGB565
{
public:
virtual bool renderNext(uint8_t &red, uint8_t &green, uint8_t &blue, uint8_t &alpha)
{
red = 0xFF;
green = 0x00;
blue = 0x00;
alpha = 0xFF;
}
};

To paint the box object from above red, put this in the header file:

Diamond10x10 box;
RedPainter redPaint;

and put this in the code:

box.setPosition(100,100,10,10);
box.setPainter(redPaint);
add(box);

Please note that it is possible to override more methods to create special painters e.g. renderInit(), however, TouchGFX has some generic painters which covers most uses.