This example shows how to draw something in the canvas every time you preview a glyph.

from random import random, randint
from vanilla import FloatingWindow, CheckBox
from mojo.events import addObserver, removeObserver
from mojo.drawingTools import *
from defconAppKit.windows.baseWindow import BaseWindowController

class BubblesPreview(BaseWindowController):

    def __init__(self):
        self.w = FloatingWindow((123, 40), "bubbles", minSize=(123, 200))

        # a checkbox to turn the tool on/off
        self.w.showBubbles = CheckBox((10, 10, -10, 20), 'show bubbles', value=True)

        # add an observer to the drawPreview event
        addObserver(self, "drawBubbles", "drawPreview")

        # open window
        self.setUpBaseWindowBehavior()
        self.w.open()

    def windowCloseCallback(self, sender):
        # remove observer when window is closed
        removeObserver(self, 'drawPreview')
        super(BubblesPreview, self).windowCloseCallback(sender)

    def drawBubbles(self, info):
        # check if checkbox is selected
        if not self.w.showBubbles.get():
            return

        # get the current glyph
        glyph = info["glyph"]

        # draw bubbles!
        stroke(None)
        if glyph is not None:
            xmin, ymin, xmax, ymax = glyph.bounds
            for i in range(10):
                for j in range(10):
                    # make random color
                    r, g, b, a = random(), random(), random(), 0.5
                    fill(r, g, b, a)
                    # make random position
                    x, y = randint(int(xmin), int(xmax)), randint(int(ymin), int(ymax))
                    # make random size
                    s = randint(16, 24)
                    # draw bubble
                    oval(x, y, s, s)

BubblesPreview()

Last edited on 27/03/2018