Skip to main content

Shapes and colors

The canvas draws rectangles (rounded or square), ellipses and lines. Anything more complicated is a vector outline.

import os

import libstb as stb

os.makedirs("out", exist_ok=True)
font = stb.Font.open("Vazirmatn-Regular.ttf")

# A flat background of 512 x 300 pixels.
background = stb.Image(memoryview(bytearray([245, 243, 238] * (512 * 300))).cast("B", (300, 512, 3)))

canvas = stb.Canvas(background)
canvas.set_font(font, 14).set_color("#333333")

# One rounded square for each way of writing a color.
swatches = [
("name", "tomato"),
("#rrggbb", "#2a9d8f"),
("#rgb", "#f90"),
("(r, g, b)", (29, 53, 87)),
("(r, g, b, a)", (230, 57, 70, 128)),
]
for i, (label, color) in enumerate(swatches):
x = 16 + i * 98
canvas.add_rect(x, 16, 88, 88).fill(color).radius(14)
canvas.add_text(label, x, 112)

# Fill and stroke, stroke only, and a line.
canvas.add_ellipse(16, 160, 130, 80).fill("#a8dadc").stroke(4, "#1d3557")
canvas.add_rect(170, 160, 130, 80).no_fill().stroke(4, "#e63946").radius(20)
canvas.add_line(330, 170, 490, 240).stroke(6, "#2a9d8f")
canvas.add_text("fill and stroke", 16, 250)
canvas.add_text("stroke only", 170, 250)
canvas.add_text("a line", 330, 250)

canvas.finish().write("out/shapes.png")
print("drawn:", len(swatches), "swatches and 3 shapes")
Output
drawn: 5 swatches and 3 shapes
out/shapes.png
out/shapes.png

Shapes​

  • add_rect(x, y, w, h) with radius(r) for rounded corners.
  • add_ellipse(x, y, w, h) fits the ellipse in the box. A circle is a square box.
  • add_line(x1, y1, x2, y2) draws a line. A line has a stroke and nothing to fill.

A shape is filled with fill(color) and outlined with stroke(width, color). A rectangle or an ellipse with only a stroke says no_fill(). The edges are smooth: a pixel the edge half covers gets half the color.

Colors​

A color is written in any of these ways, and an alpha, where there is one, makes it translucent:

FormExample
a CSS name"tomato", "white", "rebeccapurple"
#rrggbb or #rgb"#2a9d8f", "#f90"
red, green, blue(29, 53, 87)
red, green, blue, alpha(230, 57, 70, 128)

The last square in the first row is translucent, so the background shows through it.

A single number is a gray, and the same color forms work everywhere a color is taken: draw_text, Image.fill, blend backgrounds and the vector calls.

API at a glance​

Fillitem.fill(color), item.no_fill()
Strokeitem.stroke(width, color)
Rounded cornersrect.radius(px)
A color"tomato", "#2a9d8f", (r, g, b), (r, g, b, a)