Skip to content

KeyContext

Leas Porscha edited this page Aug 30, 2026 · 4 revisions

KeyContext

displaypad_lib.KeyContext — drawing surface passed to Key.render(ctx).

Each key gets its own 102×102 pixel canvas. Coordinates start at (0, 0) top-left.

Direct access

Attribute Type Description
ctx.draw PIL.ImageDraw.ImageDraw Raw PIL draw object — use any Pillow method directly
ctx.image PIL.Image.Image The underlying PIL Image for this key
ctx.width int Canvas width in pixels (102)
ctx.height int Canvas height in pixels (102)
ctx.font ImageFont Default font used by text() and center_text()

Any PIL ImageDraw method not listed here (e.g. ctx.chord(), ctx.pieslice()) is forwarded to ctx.draw automatically.

Drawing Methods

Method Description
fill(color) Fill the entire canvas with color
clear() Fill with black (alias for fill("black"))
text(x, y, text, fill, font) Draw text at (x, y)
center_text(text, y=None, fill, font) Draw text centered horizontally; optionally centered vertically
rectangle(x, y, w, h, fill) Filled rectangle at (x, y) with size (w, h)
rounded_rectangle(x, y, w, h, radius, fill) Filled rounded rectangle
ellipse(x, y, w, h, fill) Filled ellipse inside bounding box
line(x1, y1, x2, y2, fill, width) Line from (x1, y1) to (x2, y2)
polygon(points, fill) Filled polygon from list of (x, y) tuples
arc(x1, y1, x2, y2, start, end, fill, width) Arc from start to end degrees
pixel(x, y, fill) Set a single pixel
paste_image(pil_image, x, y) Paste a PIL Image at (x, y) with alpha support
apply_alpha_mask(alpha_mask) Apply an L-mode PIL Image as an alpha mask
textbbox(text, font) Return (x0, y0, x1, y1) bounding box of text
set_font(font) Change the default font

All color arguments accept both fill and color as the keyword name.

Example

class MyKey(Key):
    def render(self, ctx):
        ctx.fill("navy")
        ctx.rounded_rectangle(4, 4, ctx.width - 8, ctx.height - 8, radius=12, fill="steelblue")
        ctx.center_text("MEDIA", color="white")

        # Direct PIL access:
        ctx.draw.pieslice([10, 10, 40, 40], start=0, end=270, fill="yellow")

Clone this wiki locally