Send Close Add comments: (status displays here)
Got it!  This site "www.robinsnyder.com" uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.  Note: This appears on each machine/browser from which this site is accessed.
Python: Canvas drawing and rsCanvas module
by RS  admin@robinsnyder.com : 1024 x 640


1. Python: Canvas drawing and rsCanvas module
It is sometimes useful to create custom images in Python. The ImageDraw class in the PIL (Python Imaging Library) can be useful for this.

One can create new images or read and annotate existing images.

It as always useful to create a custom class. In this case, aggregation is used rather than inheritance.

2. Object-oriented
In object-oriented terms, the approach of inheritance derives a class (i.e., subclasses) from an ancestor or parent class.

In object-oriented terms, the approach of aggregation make another class and instance variable and then controls access to that instance variable via it's own methods, properties, etc.


3. Modules
Some modules and classes will be created and used here.

For more information on basic module and class creation, see Matplotlib: DPI tricks and plot class and rsPlot module .

4. rsCanvas module
A custom canvas class in the rsCanvas module will now be created.

5. Imports
Some imports are needed.


6. Module variables
Some module variables are needed.

The variable imagePos1 allows a series of images to be created in order.

The variable basePs1 allows the base path of the saved images to be changed.

7. The canvas class
Some methods of the canvas class are now discussed.

The ImageDraw class uses colors are represented as a tuple of the integer values for red, green, and blue. I find it easier to work with the hex forms of red, green and blue. The color method converts from hex to tuple representation.


8. Initializer
The initializer sets various instance variables which can then be changed by the calling routines as needed.

Important parts: Note: Some defaults are set, where possible, using an existing instance method.

9. Moveto



10. Lineto



11. Fonts
An ImageFont object is required to draw text. This is saved in the font1 instance variable.


12. Drawing text



13. Save the canvas
A method similar to the one used in the rsPlot module is used here to save the canvas
as an image.

Here is a code module in Lua [module rsCanvas in rsCanvas.py].

Here is the Python code [#11]


14. Output
Here is the output of the Python code.


15. Image
Canvas

16. Other capabilities
Some capabilities not shown here include the following.

17. End of page

by RS  admin@robinsnyder.com : 1024 x 640