Fill and stroke in generativepy

By Martin McBride, 2020-10-04
Tags: generativepy tutorial fill stroke rectangle
Categories: generativepy generativepy tutorial


This tutorial covers the basics of filling and stroking shapes in generativepy.

More advanced styles are covered in:

Fill and stroke example code

Here is a sample Python program for creating various filled and outlined rectangles. The code is explained later in this article:

from generativepy.drawing import make_image, setup
from generativepy.color import Color
from generativepy.geometry import Rectangle

def draw(ctx, pixel_width, pixel_height, frame_no, frame_count):
    setup(ctx, pixel_width, pixel_height, background=Color(0.8))

    Rectangle(ctx).of_corner_size((50, 50), 100, 300)\
                  .fill(Color('magenta'))

    Rectangle(ctx).of_corner_size((200, 50), 100, 300)\
                  .stroke(Color('blue'), 10)

    Rectangle(ctx).of_corner_size((350, 50), 100, 300)\
                  .stroke(Color('black'), 20)\
                  .fill(Color('yellow'))

    Rectangle(ctx).of_corner_size((500, 50), 100, 300)\
                  .fill(Color('yellow'))\
                  .stroke(Color('black'), 20)


make_image("fill-stroke-tutorial.png", draw, 650, 400)

This code is available on github in tutorial/shapes/fill-stroke.py.

Here is the resulting image:

Filling a rectangle

This section of the code draws a filled rectangle:

    Rectangle(ctx).of_corner_size((50, 50), 100, 300)\
                  .fill(Color('magenta'))

To fill the rectangle we:

  • Call Rectangle(ctx) to start the construction of the rectangle.
  • Call of_corner_size to specify a rectangle of 100 by 300 units, with its top-left corner at position (50, 50).
  • Call fill to fill the rectangle with magenta.

Stroking a rectangle

Stroking a rectangle is similar to filling a rectangle, but we use the stroke function instead of fill:

    Rectangle(ctx).of_corner_size((200, 50), 100, 300)\
                  .stroke(Color('blue'), 10)

We create a rectangle in the same way (but in a slightly different position, to the side of the previous rectangle).

The stroke function takes a colour (blue in this case) and also a parameter that indicates the thickness of 10 for the outline.

Filling and stroking a rectangle

We can apply fill and stroke to the same shape, like this:

    Rectangle(ctx).of_corner_size((350, 50), 100, 300)\
                  .stroke(Color('black'), 20)\
                  .fill(Color('yellow'))

    Rectangle(ctx).of_corner_size((500, 50), 100, 300)\
                  .fill(Color('yellow'))\
                  .stroke(Color('black'), 20)

As the code shows, we can apply stroke and fill in either order, with slightly different effects.

Fill and stroke order

This image explains how fill and stroke work when applied to a rectangle (and in fact to any other shape):

  • Area shows the base rectangle we are using.
  • Fill shows what happens when we fill the rectangle in green (with no stroke). The green fills the entire dotted area.
  • Stroke shows the rectangle being stroked, with no fill. The stroke follows the outline of the rectangle. The stroke is centred on the rectangle boundary, so it is half inside and half outside the boundary, so the overall marked area is bigger than the base rectangle.
  • Fill then stroke first fills the rectangle, then strokes it. The stroke covers part of the filled area, so the green area is smaller than the base rectangle.
  • Stroke then fill first strokes the rectangle, then fills it. The fill covers part of the stroked area, The green area is the exact size of the base rectangle, and the stroke appears to be half the requested width (because it is half covered by the fill).

There is no right or wrong way to do it, it depends on the effect you wish to achieve.

See also

If you found this article useful, you might be interested in the book NumPy Recipes or other books by the same author.

Join the PythonInformer Newsletter

Sign up using this form to receive an email when new content is added:

Popular tags

2d arrays abstract data type alignment and angle animation arc array arrays bar chart bar style behavioural pattern bezier curve built-in function callable object chain circle classes clipping close closure cmyk colour combinations comparison operator comprehension context context manager conversion count creational pattern data science data types decorator design pattern device space dictionary drawing duck typing efficiency ellipse else encryption enumerate fill filter font font style for loop formula function function composition function plot functools game development generativepy tutorial generator geometry gif global variable gradient greyscale higher order function hsl html image image processing imagesurface immutable object in operator index inner function input installing iter iterable iterator itertools join l system lambda function latex len lerp line line plot line style linear gradient linspace list list comprehension logical operator lru_cache magic method mandelbrot mandelbrot set map marker style matplotlib monad mutability named parameter numeric python numpy object open operator optimisation optional parameter or pandas partial application path pattern permutations pie chart pil pillow polygon pong positional parameter print product programming paradigms programming techniques pure function python standard library radial gradient range recipes rectangle recursion reduce regular polygon repeat rgb rotation roundrect scaling scatter plot scipy sector segment sequence setup shape singleton slice slicing sound spirograph sprite square str stream string stroke structural pattern subpath symmetric encryption template tex text text metrics tinkerbell fractal transform translation transparency triangle truthy value tuple turtle unpacking user space vectorisation webserver website while loop zip zip_longest