In this section we will create a very simple PNG image using generativepy.
Simple generativepy drawings are usually created with a single Python script that calls the generativepy module (which must be installed on your system). You will also need a couple of other modules installed (pycairo and numpy), see downloading.
Structure of a generativepy script
Here is a simple script:
from generativepy.drawing import makeImage from generativepy.color import Color def draw(canvas): canvas.stroke(Color('red')) canvas.strokeWeight(10) canvas.fill(Color('blue')) canvas.rect(50, 100, 300, 200) makeImage("simple-drawing.png", draw, pixelSize=(500, 500), background=Color('lightgrey'))
After the imports, there are two main items:
- Our drawing function. This will typically be called
draw, but it can be called anything.
- A call to the makeImage function in the
All generativepy scripts follow this basic pattern. It makes things easier and more consistent when you create differnt types of content (for example, PNG images, SVG files, animated GIFs or videos).
Here is the image it creates:
The draw function
draw function does the actual work of creating the image. It takes a single parameter
canvas, which is a
drawing.canvas object that you can use to create the drawing. Here is the function again:
def draw(canvas): canvas.stroke(Color('red')) canvas.strokeWeight(10) canvas.fill(Color('blue')) canvas.rect(50, 100, 300, 200)
This function does several things:
- It sets the stroke colour to red (this sets the colour of the outline of the rectangle)
- It sets the stroke weight to 10 pixels (this controls the width of the outline)
- It sets the fill colour to blue (this sets the colour if the inside of the rectangle)
- It draws a rectangle at pixel position (50, 100), with a width of 300 pixels and a height of 200 pixels.
Don’t worry too much about the individual functions, they will be covered in more detail in later tutorials.
The makeImage function
The call to
drawing.makeIamge looks like this:
makeImage("simple-drawing.png", draw, pixelSize=(500, 500), background=Color('lightgrey'))
It takes 4 parameters:
- The name and path of the PNG image file ypou want to create.
drawfunction we defined earlier. Notive that we use
draw()because we are passing a function object into
pixelSizeof the image, as a tuple (width, height). We will create an image of 500 pixels by 500 pixels.
backgroundcolour of the image, set to light grey.
makeImage is called it does three things:
- Creates a drawing canvas, of the required size, and fills it with the background colour.
- Passes the canvas to the supplied
drawfunction, which allows our drawing code to draw on the canvas.
- Saves the completed canvas as a PNG file.