Welcome to PyEasyGraphics documentation!

Contents:

Introduction to PyEasyGraphics

A Borland Graphics Interface like Grahics library for python

Borland Graphics Interface, also known as Turbo C Graphics, is an easy-to-use graphics library bundled with Turbo C/Turbo C++/Borland C++.

Because it is easy to learn and use, it is very good for using for kids and beginners to learn basic programming , computer graphics.

https://badge.fury.io/py/easygraphics.png https://pypip.in/d/easygraphics/badge.png

Sample program

The following code shows a moving ellipse.

from easygraphics import *

def mainloop():
    x = 0
    set_color(Color.BLUE)
    set_fill_color(Color.GREEN)

    while is_run():
        x = (x + 1) % 440
        if delay_jfps(60):
            clear_device()
            draw_ellipse(x + 100, 200, 100, 100)

def main():
    init_graph(640, 480)
    set_render_mode(RenderMode.RENDER_MANUAL)
    mainloop()
    close_graph()

easy_run(main)

Special Thanks

Some code is taken from easygui_qt and qtutils, thanks a lot!

Installation

Prerequisite:

Us pip to install PyEasyGraphics:

$ pip install easygraphics

Usage

PyEasyGraphics is suitable for beginners to learn programming, Computer Graphics, and basic game design.

References

Subpackages

easygraphics.dialog package

An easy-to-use dialogs library.

You can use it to create and show dialogs.

Based on code from EasyGUI_Qt(https://github.com/aroberge/easygui_qt/). The original EasyGUI-Qt library won’t work properly with EasyGraphics. So use this library instead.

A simple example:

>>> from easygraphics.dialog import *
>>> name=get_string("name")
>>> show_message("Your name is "+name)
Functions
easygraphics.dialog.set_dialog_font_size(size: int)

Set font size of the dialogs.

Parameters:size – font size
>>> from easygraphics.dialog import *
>>> set_dialog_font_size(18)
>>> show_message("font setted!")
easygraphics.dialog.show_message(message: str = 'Message', title: str = 'Title')

Simple message box.

Parameters:
  • message – message string
  • title – window title
>>> from easygraphics.dialog import *
>>> show_message()
_images/show_message.png
easygraphics.dialog.show_text(title: str = 'Title', text: str = '', width: int = 720, height: int = 450)

Displays some text in a window.

Parameters:
  • title – the window title
  • text – a string to display in the window.
  • width – width of the dialog window
  • height – height of the dialog window
>>> from easygraphics.dialog import *
>>> show_text("Hello","Hello world!")
_images/show_text.png
easygraphics.dialog.show_code(title: str = 'Title', code: str = '', width: int = 720, height: int = 450)

Displays some text in a window, in a monospace font.

Parameters:
  • title – the window title
  • code – a string to display in the window.
  • width – width of the dialog window
  • height – height of the dialog window
_images/show_code.png
easygraphics.dialog.show_file(file_name: str = None, title: str = 'Title', file_type: str = 'text', width: int = 720, height: int = 450)

Displays a file in a window. While it looks as though the file can be edited, the only changes that happened are in the window and nothing can be saved.

Parameters:
  • title – the window title
  • file_name – the file name, (path) relative to the calling program
  • file_type – possible values: text, code, html, python.
  • width – width of the dialog window
  • height – height of the dialog window

By default, file_type is assumed to be text; if set to code, the content is displayed with a monospace font and, if set to python, some code highlighting is done. If the file_type is html, it is processed assuming it follows html syntax.

Note: a better Python code hightlighter would be most welcome!

>>> from easygraphics.dialog import *
>>> show_file()
_images/show_file.png
easygraphics.dialog.show_objects(datas: Sequence[T_co], fields: Sequence[str] = None, field_names: Sequence[str] = None, title: str = 'Title', width: int = 720, height: int = 450, enable_sorting=False)

Displays list of objects in a table

>>> from easygraphics.dialog import *
>>> class Person:
>>>     def __init__(self,name,age,sex):
>>>         self.name=name
>>>         self.age = age
>>>         self.sex = sex
>>> objs = [Person("Jack", 22, "M"), Person("Micheal", 40, "F"), Person("David", 24, "M")]
>>> show_objects(title="peoples",datas=objs,fields=["name","age","sex"],field_names=["NAME","AGE","SEX"])
_images/show_objects.png
Parameters:
  • datas – the object list to show
  • fields – fields to show of the object
  • field_names – the field names displayed on the table header
  • title – title of the dialog window
  • width – width of the dialog window
  • height – height of the dialog window
  • enable_sorting – if data can be sorted by clicking the column name
easygraphics.dialog.get_abort(message: str = 'Major problem - or at least we think there is one...', title: str = 'Major problem encountered!')

Displays a message about a problem. If the user clicks on “abort”, sys.exit() is called and the program ends. If the user clicks on “ignore”, the program resumes its execution.

Parameters:
  • title – the window title
  • message – the message to display
>>> from easygraphics.dialog import *
>>> get_abort()
_images/get_abort.png
easygraphics.dialog.get_choice(message: str = 'Select one item', title: str = 'Title', choices: List[str] = None) → Optional[str]

Simple dialog to ask a user to select an item within a drop-down list

Parameters:
  • message – Message displayed to the user, inviting a response
  • title – Window title
  • choices – iterable (list or tuple) containing the names of the items that can be selected.
Returns:

a string, or None if “cancel” is clicked or window is closed.

>>> from easygraphics.dialog import *
>>> choices = ["CPython", "Pypy", "Jython", "IronPython"]
>>> reply = get_choice("What is the best Python implementation", choices=choices)
_images/get_choice.png
easygraphics.dialog.get_color_hex(color='white') → Optional[str]

Using a color dialog, returns a color in hexadecimal notation i.e. a string ‘#RRGGBB’ or “None” if color dialog is dismissed.

>>> from easygraphics.dialog import *
>>> color = get_color_hex()
_images/select_color.png
easygraphics.dialog.get_color_rgb(color='white') -> (<class 'int'>, <class 'int'>, <class 'int'>)

Using a color dialog, returns a color in rgb notation i.e. a tuple (r, g, b) or “None” if color dialog is dismissed.

>>> from easygraphics.dialog import *
>>> color = get_color_rgb()
_images/select_color_fr.png
easygraphics.dialog.get_color(color='white') → <sphinx.ext.autodoc.importer._MockObject object at 0x7ff5951f07d0>

Display a color picker and return the selected color

>>> from easygraphics.dialog import *
>>> color = get_color()
_images/select_color_fr.png
Returns:the color selected
easygraphics.dialog.get_continue_or_cancel(question: str = 'Processed will be cancelled!', title: str = 'Title', continue_button_text: str = 'Continue', cancel_button_text: str = 'Cancel') → bool

Continue or cancel question, shown as a warning (i.e. more urgent than simple message)

Parameters:
  • question – Question (string) asked
  • title – Window title (string)
  • continue_button_text – text to display on button
  • cancel_button_text – text to display on button
Returns:

True for “Continue”, False for “Cancel”

>>> from easygraphics.dialog import *
>>> choice = get_continue_or_cancel()
_images/get_continue_or_cancel.png
easygraphics.dialog.get_date(title: str = 'Select Date') → datetime.date

Calendar widget

Parameters:title – window title
Returns:the selected date as a datetime.date instance
>>> from easygraphics.dialog import *
>>> date = get_date()
_images/get_date.png
easygraphics.dialog.get_directory_name(title: str = 'Get directory') → str

Gets the name (full path) of an existing directory

Parameters:title – Window title
Returns:the name of a directory or an empty string if cancelled.
>>> from easygraphics.dialog import *
>>> get_directory_name()
_images/get_directory_name.png

By default, this dialog initially displays the content of the current working directory.

easygraphics.dialog.get_file_names(title: str = 'Get existing file names', filter: str = 'All Files (*.*)') → str

Gets the names (full path) of existing files

Parameters:
  • title – Window title
  • filter – file filter
Returns:

the list of names (paths) of files selected. (It can be an empty list.)

>>> from easygraphics.dialog import *
>>> get_file_names()
_images/get_file_names.png

By default, this dialog initially displays the content of the current working directory.

easygraphics.dialog.get_float(message: str = 'Choose a number', title: str = 'Title', default_value: float = 0.0, min_: float = -10000, max_: float = 10000, decimals: int = 3) → Optional[float]

Simple dialog to ask a user to select a floating point number within a certain range and a maximum precision.

Parameters:
  • message – Message displayed to the user, inviting a response
  • title – Window title
  • default_value – Default value for value appearing in the text box; set to the closest of min_ or max_ if outside of allowed range.
  • min – Minimum value allowed
  • max – Maximum value allowed
  • decimals – Indicate the maximum decimal precision allowed
Returns:

a floating-point number, or None if “cancel” is clicked or window is closed.

>>> from easygraphics.dialog import *
>>> number = get_float()
_images/get_float.png

Note: depending on the locale of the operating system where this is used, instead of a period being used for indicating the decimals, a comma may appear instead; this is the case for the French version of Windows for example. Therefore, entry of floating point values in this situation will require the use of a comma instead of a period. However, the internal representation will still be the same, and the number passed to Python will be using the familar notation.

easygraphics.dialog.get_int(message: str = 'Choose a number', title: str = 'Title', default_value: int = 1, min_: int = 0, max_: int = 100, step: int = 1) → Optional[int]

Simple dialog to ask a user to select an integer within a certain range.

Note: get_int() and get_integer() are identical.

Parameters:
  • message – Message displayed to the user, inviting a response
  • title – Window title
  • default_value – Default value for integer appearing in the text box; set to the closest of min_ or max_ if outside of allowed range.
  • min – Minimum integer value allowed
  • max – Maximum integer value allowed
  • step – Indicate the change in integer value when clicking on arrows on the right hand side
Returns:

an integer, or None if “cancel” is clicked or window is closed.

>>> from easygraphics.dialog import *
>>> number = get_int()
_images/get_int.png

If default_value is larger than max_, it is set to max_; if it is smaller than min_, it is set to min_.

>>> number = get_integer("Enter a number", default_value=125)
_images/get_int2.png
easygraphics.dialog.get_integer(message: str = 'Choose a number', title: str = 'Title', default_value: int = 1, min_: int = 0, max_: int = 100, step: int = 1) → Optional[int]

Simple dialog to ask a user to select an integer within a certain range.

Note: get_int() and get_integer() are identical.

Parameters:
  • message – Message displayed to the user, inviting a response
  • title – Window title
  • default_value – Default value for integer appearing in the text box; set to the closest of min_ or max_ if outside of allowed range.
  • min – Minimum integer value allowed
  • max – Maximum integer value allowed
  • step – Indicate the change in integer value when clicking on arrows on the right hand side
Returns:

an integer, or None if “cancel” is clicked or window is closed.

>>> from easygraphics.dialog import *
>>> number = get_int()
_images/get_int.png

If default_value is larger than max_, it is set to max_; if it is smaller than min_, it is set to min_.

>>> number = get_integer("Enter a number", default_value=125)
_images/get_int2.png
easygraphics.dialog.get_list_of_choices(title: str = 'Title', choices: List[str] = None) → easygraphics.dialog._indexed_order_list.IndexedOrderedDict

Show a list of possible choices to be selected.

Parameters:
  • title – Window title
  • choices – iterable (list, tuple, …) containing the choices as strings
Returns:

a list of selected items, otherwise an empty list.

>>> from easygraphics.dialog import *
>>> choices = get_list_of_choices()
_images/get_list_of_choices.png
easygraphics.dialog.get_many_strings(title: str = 'Title', labels: List[str] = None, masks: List[bool] = None) → easygraphics.dialog._indexed_order_list.IndexedOrderedDict

Multiple strings input

Parameters:
  • title – Window title
  • labels – an iterable containing the labels for to use for the entries
  • masks – optional parameter.
Returns:

An ordered dict containing the labels as keys, and the input from the user (empty string by default) as value

The parameter masks if set must be an iterable of the same length as choices and contain either True or False as entries indicating if the entry of the text is masked or not. For example, one could ask for a username and password using get_many_strings as follows [note that get_username_password exists and automatically takes care of specifying the masks and is a better choice for this use case.]

>>> from easygraphics.dialog import *
>>> labels = ["User name", 'Password']
>>> masks = [False, True]
>>> reply = get_many_strings(labels=labels, masks=masks)
>>> reply
OrderedDict([('User name', 'aroberge'), ('Password', 'not a good password')])
_images/get_many_strings.png
easygraphics.dialog.get_new_password(title: str = 'Title', labels: List[str] = None) → easygraphics.dialog._indexed_order_list.IndexedOrderedDict

Change password input box.

Parameters:
  • title – Window title
  • labels – an iterable containing the labels for “Old password” and “New password” and “Confirm new password”. All three labels must be different strings as they are used as keys in a dict - however, they could differ only by a space.
Returns:

An ordered dict containing the fields item as keys, and the input from the user as values.

Note: this function is a special case of get_many_strings where the required masks are provided automatically..

>>> from easygraphics.dialog import *
>>> reply = get_new_password()
_images/get_new_password.png
easygraphics.dialog.get_open_file_name(title: str = 'Get file name for open', filter: str = 'All Files (*.*)') → str

Get a file name for open

Parameters:
  • title – title of the dialog
  • filter – file filter
Returns:

the file name

easygraphics.dialog.get_password(message: str = 'Enter your password', title: str = 'Title') → Optional[str]

Simple password input box. Used to query the user and get a string back.

Parameters:
  • message – Message displayed to the user, inviting a response
  • title – Window title
Returns:

a string, or None if “cancel” is clicked or window is closed.

>>> from easygraphics.dialog import *
>>> password = get_password()
_images/get_password.png
easygraphics.dialog.get_save_file_name(title: str = 'File name to save', filter: str = 'All Files (*.*)') → str

Gets the name (full path) of of a file to be saved.

Parameters:
  • title – Window title
  • title – Window title
Returns:

the name (path) of file selected

The user is warned if the file already exists and can choose to cancel. However, this dialog actually does NOT save any file: it only return a string containing the full path of the chosen file.

>>> from easygraphics.dialog import *
>>> get_save_file_name()
_images/get_save_file_name.png

By default, this dialog initially displays the content of the current working directory.

easygraphics.dialog.get_string(message: str = 'Enter your response', title: str = 'Title', default_response: str = '') → Optional[str]

Simple text input box. Used to query the user and get a string back.

Parameters:
  • message – Message displayed to the user, inviting a response
  • title – Window title
  • default_response – default response appearing in the text box
Returns:

a string, or None if “cancel” is clicked or window is closed.

>>> from easygraphics.dialog import *
>>> reply = get_string()
_images/get_string.png
>>> reply = get_string("new message", default_response="ready")
_images/get_string2.png
easygraphics.dialog.get_username_password(title: str = 'Title', labels: List[str] = None) → easygraphics.dialog._indexed_order_list.IndexedOrderedDict

User name and password input box.

Parameters:
  • title – Window title
  • labels – an iterable containing the labels for “user name” and “password”; if the value not specified, the default values will be used.
Returns:

An ordered dict containing the fields item as keys, and the input from the user (empty string by default) as value

Note: this function is a special case of get_many_strings where the required masks are provided automatically..

>>> from easygraphics.dialog import *
>>> reply = get_username_password()
>>> reply
OrderedDict([('User name', 'aroberge'), ('Password', 'not a good password')])
_images/get_username_password.png
easygraphics.dialog.get_yes_or_no(question: str = 'Answer this question', title: str = 'Title') → Optional[bool]

Simple yes or no question.

Parameters:
  • question – Question (string) asked
  • title – Window title (string)
Returns:

True for “Yes”, False for “No”, and None for “Cancel”.

>>> from easygraphics.dialog import *
>>> choice = get_yes_or_no()
_images/yes_no_question.png
easygraphics.dialog.show_image_dialog(image: <sphinx.ext.autodoc.importer._MockObject object at 0x7ff58e414290>, title: str = 'Title')

Display the image in a dialog.

Parameters:
  • image – the image to be displayed
  • title – Window title
easygraphics.dialog.show_table(datas: Sequence[T_co], fields: Sequence[str] = None, field_names: Sequence[str] = None, title: str = 'Title', width: int = 720, height: int = 450, enable_sorting=False)

Displays list of objects in a table

>>> from easygraphics.dialog import *
>>> class Person:
>>>     def __init__(self,name,age,sex):
>>>         self.name=name
>>>         self.age = age
>>>         self.sex = sex
>>> objs = [Person("Jack", 22, "M"), Person("Micheal", 40, "F"), Person("David", 24, "M")]
>>> show_objects(title="peoples",datas=objs,fields=["name","age","sex"],field_names=["NAME","AGE","SEX"])
_images/show_objects.png
Parameters:
  • datas – the object list to show
  • fields – fields to show of the object
  • field_names – the field names displayed on the table header
  • title – title of the dialog window
  • width – width of the dialog window
  • height – height of the dialog window
  • enable_sorting – if data can be sorted by clicking the column name
easygraphics.dialog.show_lists_table(*args, column_names: List[str] = None, title: str = 'Title', width: int = 720, height: int = 450)

Displays list of datas in a table

>>> from easygraphics.dialog import *
>>> x=[1,2,3,4]
>>> y=["hah","jack","marry"]
>>> show_lists_table(x,y,column_names=['x','y'])
.. image:: ../../docs/images/dialogs/show_lists_table.png
Parameters:
  • args – the lists to show
  • column_names – the column names displayed on the table header
  • title – title of the dialog window
  • width – width of the dialog window
  • height – height of the dialog window
easygraphics.dialog.show_html(title: str = 'Title', text: str = '', width: int = 720, height: int = 450)

Displays some html text in a window.

Parameters:
  • title – the window title
  • text – a string to display in the window.
  • width – width of the dialog window
  • height – height of the dialog window
>>> from easygraphics.dialog import *
>>> show_html()
apis/../../docs/images/dialogs/show_html.png
class easygraphics.dialog.FileFilter
AllFiles = 'All Files (*.*)'
CSVFiles = 'CSV Files (*.csv)'
ImageFiles = 'Image Files (*.png *.gif *.jpg *.webp *.bmp)'
PythonFiles = 'Python Files (*.py)'
TxtFiles = 'Text Files (*.txt)'

easygraphics.legacy package

The BGI compatible module.

This module redefines the functions using the same names used in the BGI, for easily porting BGI graphics programs to python.

Functions
easygraphics.legacy.SOLID_LINE

Used by autodoc_mock_imports.

easygraphics.legacy.DOTTED_LINE

Used by autodoc_mock_imports.

easygraphics.legacy.CENTER_LINE

Used by autodoc_mock_imports.

easygraphics.legacy.DASHED_LINE

Used by autodoc_mock_imports.

easygraphics.legacy.USERBIT_LINE

Used by autodoc_mock_imports.

easygraphics.legacy.NULL_LINE

Used by autodoc_mock_imports.

easygraphics.legacy.COPY_PUT

Used by autodoc_mock_imports.

easygraphics.legacy.XOR_PUT

Used by autodoc_mock_imports.

easygraphics.legacy.AND_PUT

Used by autodoc_mock_imports.

easygraphics.legacy.OR_PUT

Used by autodoc_mock_imports.

easygraphics.legacy.NOT_PUT

Used by autodoc_mock_imports.

easygraphics.legacy.arc(x: int, y: int, start: int, end: int, rad: int, img: easygraphics.image.Image = None)

Draw a Circular Arc

arc() draws the outline of an arc in the current drawing color. The circular arc is centered at (‘x’,’y’) with a radius of ‘rad’. The arc travels from ‘start’ to ‘end.

Note: ‘start’ and ‘end’ are in degrees; 0 degrees is a 3
o’clock.
easygraphics.legacy.bar(left: float, top: float, right: float, bottom: float, image: easygraphics.image.Image = None)

Draws a rectangle with upper left corner at (left, top) and lower right corner at (right,bottom).

The rectangle doesn’t have outline.

Parameters:
  • left – x coordinate value of the upper left corner
  • top – y coordinate value of the upper left corner
  • right – x coordinate value of the lower right corner
  • bottom – y coordinate value of the lower right corner
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.legacy.circle(x: float, y: float, r: float, image: easygraphics.image.Image = None)

Draw a circle outline centered at (x,y) with radius r.

The circle is not filled.

Parameters:
  • x – x coordinate value of the circle’s center
  • y – y coordinate value of the circle’s center
  • r – radius of the circle
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.legacy.cleardevice(image: easygraphics.image.Image = None)

Clear the image to show the background.

Parameters:image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.legacy.clearviewport(image: easygraphics.image.Image = None)

clear view port to show the background.

Parameters:image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.legacy.closegraph()

Close the graphics windows.

The program will exit too.

>>> from easygraphics import *
>>> init_graph(800,600)
>>> pause()
>>> close_graph()
easygraphics.legacy.drawpoly(*end_points, image: easygraphics.image.Image = None)

Draw a poly line.

“end_points” is a 2D points list. Each 2 values in the list make a point. A poly line will be drawn to connect adjacent end_points defined by the the list.

For examples , if “end_points” is [50,50,550,350, 50,150,550,450, 50,250,550,550], draw_poly_line() will draw 5 lines: (50,50) to (550,350), (550,350) to (50,150), (50,150) to (550,450), (550,540) to (50,250) and(50,250) to (550,550).

>>> from easygraphics import *
>>> init_graph(600,600)
>>> draw_poly_line(50,50,550,350,50,150,550,450,50,250,550,550)
>>> pause()
>>> close_graph()
Parameters:
  • end_points – point value list
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.legacy.ellipse(x: float, y: float, start_angle: float, end_angle: float, radius_x: float, radius_y: float, image: easygraphics.image.Image = None)

Draw an elliptical arc from start_angle to end_angle. The base ellipse is centered at (x,y) which radius on x-axis is radius_x and radius on y-axis is radius_y.

Note: Positive values for the angles mean counter-clockwise while negative values mean the clockwise direction. Zero degrees is at the 3 o’clock position.
Parameters:
  • x – x coordinate value of the ellipse’s center
  • y – y coordinate value of the ellipse’s center
  • start_angle – start angle of the arc
  • end_angle – end angle of the arc
  • radius_x – radius on x-axis of the ellipse
  • radius_y – radius on y-axis of the ellipse
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.legacy.fillellipse(x, y, radius_x, radius_y, image: easygraphics.image.Image = None)

Draw an ellipse centered at (x,y) , radius on x-axis is radius_x, radius on y-axis is radius_y.

The ellipse is filled and has outline.

Parameters:
  • x – x coordinate value of the ellipse’s center
  • y – y coordinate value of the ellipse’s center
  • radius_x – radius on x-axis of the ellipse
  • radius_y – radius on y-axis of the ellipse
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.legacy.fillpoly(*vertices, image: easygraphics.image.Image = None)

Fill a polygon.

“vertices” is a 2D point list. Each 2 values in the list make a point. A polygon will be drawn to connect adjacent points defined by the the list.

For examples , if “vertices” is [50,50,550,350, 50,150], fill_polygon() will fill a triangle with vertices at (50,50) , (550,350) and (50,150).

The polygon doesn’t have outline.

>>> from easygraphics import *
>>> init_graph(600,600)
>>> set_fill_color(Color.LIGHT_MAGENTA)
>>> fill_polygon(50,50,550,350,50,150)
>>> pause()
>>> close_graph()
Parameters:
  • vertices – point value list
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.legacy.floodfill(x: int, y: int, border_color, image: easygraphics.image.Image = None)

Flood fill the image starting from(x,y) and ending at borders with border_color.

The fill region border must be closed,or the whole image will be filled!

Parameters:
  • x – x coordinate value of the start point
  • y – y coordinate value of the start point
  • border_color – color of the fill region border
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.legacy.getbkcolor(image: easygraphics.image.Image = None) → <sphinx.ext.autodoc.importer._MockObject object at 0x7f50882d5150>

Get the background color of the image.

Parameters:image – the target image whose background color is to be gotten. None means it is the target image (see set_target() and get_target()).
Returns:background color of the specified image
easygraphics.legacy.getcolor(image: easygraphics.image.Image = None) → <sphinx.ext.autodoc.importer._MockObject object at 0x7f50882d5150>

Get the foreground (drawing) color of the specified image.

it will be used when drawing lines or shape outlines

Parameters:image – the target image whose foreground color is to be gotten. None means it is the target image (see set_target() and get_target()).
Returns:foreground color of the specified image
easygraphics.legacy.getfillsettings(img: easygraphics.image.Image = None)

get fill settings

Returns:fill style, fill color
easygraphics.legacy.getimage(left: int, top: int, width: int, height: int, target_img: easygraphics.image.Image)

Capture specified region on the graphics windows to target image.

Parameters:
  • left – x coordinate of the capture region’s upper left corner
  • top – y coordinate of the capture region’s upper left corner
  • width – width of the capture region
  • height – height of the capture region
  • target_img – image to save the capture
easygraphics.legacy.getlinesettings(img: easygraphics.image.Image = None)

Get line settings

Returns:line style, line width
easygraphics.legacy.getmaxx(img: easygraphics.image.Image = None) → int

Get the maximum x value of graphics screen

Returns:the maximum x value
easygraphics.legacy.getmaxy(img: easygraphics.image.Image = None)

Get the maximum y value of graphics screen

Returns:the maximum y value
easygraphics.legacy.getpixel(x: int, y: int, image: easygraphics.image.Image = None) → <sphinx.ext.autodoc.importer._MockObject object at 0x7f50882d5150>

Get a pixel’s color on the specified image.

Parameters:
  • x – x coordinate value of the pixel
  • y – y coordinate value of the pixel
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
Returns:

color of the pixel

easygraphics.legacy.getx(image: easygraphics.image.Image = None) → float

Get the x coordinate value of the current drawing position (x,y).

Some drawing functions will use the current pos to draw.(see line_to(),line_rel(),move_to(),move_rel()).

Parameters:image – the target image whose drawing pos is to be gotten. None means it is the target image (see set_target() and get_target()).
Returns:the x coordinate value of the current drawing position
easygraphics.legacy.gety(image: easygraphics.image.Image = None) → float

Get the y coordinate value of the current drawing position (x,y).

Some drawing functions will use the current pos to draw.(see line_to(),line_rel(),move_to(),move_rel()).

Parameters:image – the target image whose drawing pos is to be gotten. None means it is the target image (see set_target() and get_target()).
Returns:the y coordinate value of the current drawing position
easygraphics.legacy.initgraph(width: int = 800, height: int = 600, headless: bool = False)

Init the easygraphics system and show the graphics window.

If “headless” is True, easygraphics will run in headless mode, which means there will be no graphics window. Use this mode if you want to draw and save image to files.

Parameters:
  • width – width of the graphics window (in pixels)
  • height – height of the graphics window (in pixels)
  • headless – True to run in headless mode.
>>> from easygraphics import *
>>> init_graph(800,600) #prepare and show a 800*600 window
easygraphics.legacy.line(x1, y1, x2, y2, image: easygraphics.image.Image = None)

Draw a line from (x1,y1) to (x2,y2) on the specified image.

It’s the same with line().

Parameters:
  • x1 – x coordinate value of the start point
  • y1 – y coordinate value of the start point
  • x2 – x coordinate value of the end point
  • y2 – y coordinate value of the start point
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.legacy.linerel(dx: float, dy: float, image: easygraphics.image.Image = None)

Draw a line from the current drawing position (x,y) to (x+dx,y+dy), then set the drawing position is set to (x+dx,y+dy).

Parameters:
  • dx – x coordinate offset of the new drawing position
  • dy – y coordinate offset of the new drawing position
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.legacy.lineto(x: float, y: float, image: easygraphics.image.Image = None)

Draw a line from the current drawing position to (x,y), then set the drawing position is set to (x,y).

Parameters:
  • x – x coordinate value of the new drawing position
  • y – y coordinate value of the new drawing position
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.legacy.moverel(dx: float, dy: float, image: easygraphics.image.Image = None)

Move the drawing position by (dx,dy).

If the old position is (x,y), then the new position will be (x+dx,y+dy).

The drawing position is used by line_to(), line_rel().

Parameters:
  • dx – x coordinate offset of the new drawing position
  • dy – y coordinate offset of the new drawing position
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.legacy.moveto(x: float, y: float, image: easygraphics.image.Image = None)

Set the drawing position to (x,y).

The drawing position is used by line_to(), line_rel() and move_rel().

Parameters:
  • x – x coordinate value of the new drawing position
  • y – y coordinate value of the new drawing position
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.legacy.outtext(text: str, img: easygraphics.image.Image = None)

Display the given text on the current position

Parameters:text – text to be displayed
easygraphics.legacy.outtextxy(x: int, y: int, text: str, img: easygraphics.image.Image = None)

Display the given text on the specified position

Parameters:
  • x – x pos of the string
  • y – y pos of the string
  • text – text to be displayed
easygraphics.legacy.pieslice(x: float, y: float, start_angle: int, end_angle: int, r: float, img: easygraphics.image.Image = None)
easygraphics.legacy.putimage(left: int, top: int, src_image: easygraphics.image.Image, mode: int, dst_image: easygraphics.image.Image = None)

Puts a previously-saved bit image back onto the screen.

The coordinates (‘left’,’top’) are used to place the image on the screen.

image is a previously screen copy (using getimage()).

‘op’ determines how the color for each destination pixel is computed. This is based on the pixel already on the screen and the source pixel in memory. The available ops are COPY_PUT, XOR_PUT, OR_PUT, AND_PUT and NOT_PUT

Parameters:
  • left – left position on the screen to be copied
  • top – top position on the screen to be copied
  • src_image – the image to be copied
  • op – copy operation
easygraphics.legacy.putpixel(x: int, y: int, color, image: easygraphics.image.Image = None)

Set a pixel’s color on the specified image.

Parameters:
  • x – x coordinate value of the pixel
  • y – y coordinate value of the pixel
  • color – the color
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.legacy.rectangle(left: float, top: float, right: float, bottom: float, image: easygraphics.image.Image = None)

Draws a rectangle outline with upper left corner at (left, top) and lower right corner at (right,bottom).

The rectangle is not filled.

Parameters:
  • left – x coordinate value of the upper left corner
  • top – y coordinate value of the upper left corner
  • right – x coordinate value of the lower right corner
  • bottom – y coordinate value of the lower right corner
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.legacy.sector(x: float, y: float, start_angle: float, end_angle: float, radius_x: float, radius_y: float, image: easygraphics.image.Image = None)

Draw an elliptical pie from start_angle to end_angle. The base ellipse is centered at (x,y) which radius on x-axis is radius_x and radius on y-axis is radius_y.

The pie is filled and has outline.

Note: Positive values for the angles mean counter-clockwise while negative values mean the clockwise direction. Zero degrees is at the 3 o’clock position.
Parameters:
  • x – x coordinate value of the ellipse’s center
  • y – y coordinate value of the ellipse’s center
  • start_angle – start angle of the pie
  • end_angle – end angle of the pie
  • radius_x – radius on x-axis of the ellipse
  • radius_y – radius on y-axis of the ellipse
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.legacy.setbkcolor(color, image: easygraphics.image.Image = None)

Set and change the background color.

the possible color could be consts defined in Color class, or the color created by rgb() function, or PyQt5’s QColor , QGradient object or Qt.GlobalColor consts (see the pyqt reference).

Parameters:
  • color – the background color
  • image – the target image whose background color is to be set. None means it is the target image (see set_target() and get_target()).
easygraphics.legacy.setcolor(color, image: easygraphics.image.Image = None)

Set the foreground (drawing) color of the specified image.

it will be used when drawing lines or shape outlines.

the possible color could be consts defined in Color class, or the color created by rgb() function, or PyQt5’s QColor , QGradient object or Qt.GlobalColor consts (see the pyqt reference).

Parameters:
  • color – the foreground color
  • image – the target image whose foreground color is to be set. None means it is the target image (see set_target() and get_target()).
easygraphics.legacy.setfillstyle(pattern, color, img: easygraphics.image.Image = None)

Set fill pattern :param pattern: fill style :param color: fill color

easygraphics.legacy.setlinestyle(linstyle, upattern, thickness, img: easygraphics.image.Image = None)

Set line style :param linstyle: line style :param upattern: no use :param thickness: line width :param img: :return:

easygraphics.legacy.settextjustify(horiz: int, vert: int)

Set Current Text Justification Settings

settextjustify() controls text justification with respect to the current position (CP). The text is justified horizontally and vertically.

Constants of the text_just for ‘horiz’ are: LEFT_TEXT, CENTER_TEXT, RIGHT_TEXT

Constants of the text_just for ‘vert’ are: TOP_TEXT, CENTER_TEXT, BOTTOM_TEXT

easygraphics.legacy.setviewport(left: int, top: int, right: int, bottom: int, clip: bool = True, image: easygraphics.image.Image = None)

Set the view port of the the specified image.

View port is the drawing zone on the image.

>>> from easygraphics import *
>>> init_graph(800,600)
>>> draw_rect(100,100,300,300)
>>> set_view_port(100,100,300,300)
>>> circle(100,100,50)
>>> circle(100,100,100)
>>> circle(100,100,120)
>>> pause()
>>> close_graph()
Parameters:
  • left – left of the view port rectangle
  • top – top of the view port rectangle
  • right – right of the view port rectangle
  • bottom – bottom of the view port rectangle
  • clip – if True, drawings outside the port rectangle will be clipped
  • image – the target image whose view port is to be gotten. None means it is the target image (see set_target() and get_target()).
easygraphics.legacy.setwritemode(mode, img: easygraphics.image.Image = None)

Set Write Mode for Line Drawing

This function sets the writing mode for line drawing. If mode is 0, lines overwrite the screen’s current contents. On the other hand, If mode is 1, an exclusive OR (XOR) is done.

easygraphics.legacy.textheight(image: easygraphics.image.Image = None) → int

Return height of the text (font height).

Parameters:image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
Returns:height of the text (font height)
easygraphics.legacy.textwidth(text: str, image: easygraphics.image.Image = None) → int

Return width of the text.

Parameters:
  • text – the text
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
Returns:

width of the text

easygraphics.music package

A simple music play module.

Functions

A simple music play library.

You can use it to load and play music files.

A simple example:

>>> from easygraphics.music import *
>>> # For legal reasons please prepare a music file by yourself
>>> load_music("test.mp3")
>>> play_music()
>>> close_music()
easygraphics.music.load_music(filename: str) → None

Load a music file for playback.

If music playback device is note initialized, it will be initialized automatically.

Use play_music() to play the music.

Parameters:filename – the music file to play
easygraphics.music.close_music()

Close the music playback device.

easygraphics.music.play_music(loops: int = 0, start: float = 0.0) → None

Play the music.

Parameters:
  • loops – loops. 0 means no loop
  • start – start position of the music
easygraphics.music.pause_music() → None

Pause the music playback.

easygraphics.music.unpause_music() → None

Unpause the music playback.

easygraphics.music.stop_music() → None

Stop the music playback.

easygraphics.music.queue_music(filename: str)

Add music to the playing queue.

Parameters:filename – the music file to be queued.
easygraphics.music.is_music_playing() → bool

Get if the music is playing.

Returns:True if is playing, False if is not.
easygraphics.music.get_music_pos() → float

Get current music playback position .

Returns:current position
easygraphics.music.get_music_volume() → int

Return the music playback volume.

Returns:the playback volume.
easygraphics.music.set_music_pos(pos: float)

Set current music play position.

Parameters:pos – the position to set.
easygraphics.music.set_music_volume(volume: int)

Set volume of the music playback.

Parameters:volume – volume of the playback
easygraphics.music.fade_out_music(time: float)

Fade out and stop the music.

Parameters:time – fade out time (in milliseconds)

easygraphics.processing package

A Processing (http://processing.org) like animation graphics module

from easygraphics import *
from easygraphics.processing import *
import math

x_spacing = 16  # How far apart should each horizontal location be spaced
theta = 0  # Start angle at 0
amplitude = 75  # Height of wave
period = 500  # How many pixels before the wave repeats

dx = (2 * math.pi / period) * x_spacing

def setup():
    global w
    set_size(640, 360)
    translate(0, get_height() // 2)
    set_background_color("black")
    set_fill_color("white")
    w = get_width() + 16  # Width of entire wave

def draw():
    global theta
    theta += 0.02
    clear_device()
    x = theta
    for i in range(w // x_spacing):
        y = math.sin(x) * amplitude
        fill_circle(i * x_spacing, y, 8)
        x += dx

run_app(globals())
_images/sine.wave.png
Function list
Main App
run_app
Control and Settings
full_screen
get_frame_rate
loop
mouse_pressed
mouse_x
mouse_y
noloop
prev_mouse_x
prev_mouse_y
redraw
set_frame_rate
set_size
Functions
easygraphics.processing.redraw()

Call draw() to draw a frame once.

You must NOT redefine this function!

easygraphics.processing.loop()

Start looping.

easygraphics.processing.noloop()

Stop looping.

easygraphics.processing.run_app(_globals)

Run the processing app.

Parameters:_globals – the python globals dict.
easygraphics.processing.set_size(width: int, height: int)

Open a canvas window with the specified size.

Parameters:
  • width – width of the canvas
  • height – height of the canvas
easygraphics.processing.full_screen()

Open a full screen canvas.

easygraphics.processing.draw()

Draw an animation frame.

You should redefine this function in your program.

Returns:
easygraphics.processing.setup()

Set up the processing context.

You should redefine this function in your program.

easygraphics.processing.set_frame_rate(fps: int)

Set the animation frame rate (fps).

Parameters:fps – the frame rate
easygraphics.processing.get_frame_rate() → int

Get the animation frame rate (fps).

Returns:the frame rate
easygraphics.processing.on_mouse_wheel(e: <sphinx.ext.autodoc.importer._MockObject object at 0x7f5087bda550>)

The mouse wheel event handler.

You can redefine this function to handle the mouse wheel event.

easygraphics.processing.on_mouse_dragged()

The mouse drag event handler.

You can redefine this function to handle the mouse drag event.

easygraphics.processing.on_mouse_released()

The mouse release event handler.

You can redefine this function to handle the mouse release event.

easygraphics.processing.on_mouse_pressed()

The mouse press event handler.

You can redefine this function to handle the mouse press event.

easygraphics.processing.on_mouse_clicked()

The mouse click event handler.

You can redefine this function to handle the mouse click event.

class easygraphics.processing.ProcessingWidget(*args, auto_start=True, **kwargs)

The processing-like widget.

draw()

Draw an animation frame.

You should override this method.

full_screen()

Set the canvas size to full screen.

get_canvas() → easygraphics.image.Image

Get the canvas image.

Returns:the canvas image
get_frame_rate() → int

Get the animation frame rate (fps).

Returns:the frame rate
keyPressEvent(e: <sphinx.ext.autodoc.importer._MockObject object at 0x7f50785441d0>)
loop()

Start looping.

mouseMoveEvent(e: <sphinx.ext.autodoc.importer._MockObject object at 0x7f50785441d0>)
mousePressEvent(e: <sphinx.ext.autodoc.importer._MockObject object at 0x7f50785441d0>)
mouseReleaseEvent(e: <sphinx.ext.autodoc.importer._MockObject object at 0x7f50785441d0>)
noloop()

Stop looping.

on_mouse_clicked()

The mouse click event handler.

You can override it to handle the mouse click event.

on_mouse_dragged()

The mouse drag event handler.

You can override it to handle the mouse drag event.

on_mouse_pressed()

The mouse press event handler.

You can override it to handle the mouse press event.

on_mouse_released()

The mouse release event handler.

You can override it to handle the mouse release event.

on_mouse_wheel(e: <sphinx.ext.autodoc.importer._MockObject object at 0x7f50785441d0>)

The mouse wheel event handler.

You can override it to handle the mouse wheel event.

paintEvent(e: <sphinx.ext.autodoc.importer._MockObject object at 0x7f50785441d0>)
redraw()

Call draw() to draw a frame once.

set_frame_rate(fps)

Set the animation frame rate (fps).

Parameters:fps – the frame rate
set_size(width: int, height: int)

Set the canvas size.

Parameters:
  • width – width of the canvas.
  • height – height of the canvas.
setup()

Setup the drawing context.

You should override this method.

start()

Start the animation manually.

wheelEvent(e: <sphinx.ext.autodoc.importer._MockObject object at 0x7f50785441d0>)

easygraphics.turtle package

The turtle graphics package.

The turtle graphics is a classic and popular way to introducing programming to kids.

In the turtle graphics, you control a turtle to move around the graphics window. The traces left by its move form drawings.

Note that in the turtle graphics, the origin (0,0) is in the center of the graphics window, and Y-axis is bottom-up.

from easygraphics.turtle import *

def polyspi(side, angle, inc):
    while is_run():
        fd(side)
        rt(angle)
        side += inc

create_world(800, 600)
set_speed(100)
polyspi(0, 117, 5)
close_world()
_images/infinite.png
Functions
easygraphics.turtle.create_world(width: int = 800, height: int = 600) → None

Create an world for turtle drawing.

Parameters:
  • width – width of the graphics window
  • height – height of the graphics window
easygraphics.turtle.close_world() → None

Close the turtle world and the graphics window.

easygraphics.turtle.forward(distance: float)

Move the turtle forward by the specified distance, in the direction the turtle is heading.

Parameters:distance – the distance to move
easygraphics.turtle.fd(distance: float)

Move the turtle forward by the specified distance, in the direction the turtle is heading.

Parameters:distance – the distance to move
easygraphics.turtle.backward(distance: float)

Move the turtle backward by the specified distance, in the direction the turtle is heading.

Parameters:distance – the distance to move
easygraphics.turtle.back(distance: float)

Move the turtle backward by the specified distance, in the direction the turtle is heading.

Parameters:distance – the distance to move
easygraphics.turtle.bk(distance: float)

Move the turtle backward by the specified distance, in the direction the turtle is heading.

Parameters:distance – the distance to move
easygraphics.turtle.left_turn(degree: float)

Turn turtle left (counter-clockwise) by “degree” degree.

Parameters:degree – the degree to turn
easygraphics.turtle.lt(degree: float)

Turn turtle left (counter-clockwise) by “degree” degree.

Parameters:degree – the degree to turn
easygraphics.turtle.right_turn(degree: float)

Turn turtle right (clockwise) by “degree” degree.

Parameters:degree – the degree to turn
easygraphics.turtle.rt(degree: float)

Turn turtle right (clockwise) by “degree” degree.

Parameters:degree – the degree to turn
easygraphics.turtle.left(degree: float)

Turn turtle left (counter-clockwise) by “degree” degree.

Parameters:degree – the degree to turn
easygraphics.turtle.right(degree: float)

Turn turtle right (clockwise) by “degree” degree.

Parameters:degree – the degree to turn
easygraphics.turtle.clear_screen()

Delete all drawings from the screen and reset turtles to its original state.

easygraphics.turtle.cs()

Delete all drawings from the screen and reset turtles to its original state.

easygraphics.turtle.gotoxy(x: float, y: float)

Move the turtle to point (x,y). Will leave traces if the pen is down.

Parameters:
  • x – x coordinate value of the destination point.
  • y – x coordinate value of the destination point.
easygraphics.turtle.home()

Move the turtle back to the origin(0,0), and heading up. Will leave traces if the pen is down.

easygraphics.turtle.turn_to(angle)

Turn the angle to orient to the specified angle.

Parameters:angle – the new heading angle (in degrees).
easygraphics.turtle.facing(x: float, y: float)

Turn the turtle to face the point(x,y).

Parameters:
  • x – x coordinate value of the target point
  • y – y coordinate value of the target point
easygraphics.turtle.begin_fill()

Begin to record the turtle’s shape drawing path for filling.

easygraphics.turtle.end_fill()

Fill the shape enclosed by the turtle’s drawing path after the last call to begin_fill.

easygraphics.turtle.setxy(x: float, y: float)

Set the turtle’s current position to point (x,y). Will not leave traces.

Parameters:
  • x – x coordinate value of the destination point.
  • y – y coordinate value of the destination point.
easygraphics.turtle.set_heading(angle)

Set the angle current heading to the specified angle.

Parameters:angle – the new heading angle (in degrees).
easygraphics.turtle.move_arc(radius: float, angle: float = 360)

Move the turtle in a arc path.

The center is radius units left of the turtle. That is, if radius > 0, the center is on the left of the turtle; if radius < 0, the center is on the right of the turtle.

If angle > 0, the turtle moves forward around the center; if angle < 0, the turtle moves backward around the center. So:

  • if angle > 0 and radius > 0, the turtle moves forward and turns counter-clockwise;
  • if angle > 0 and raidus < 0, the turtle move forward and turns clockwise;
  • if angle <0 and radius > 0, the turtle moves backward and turns clockwise;
  • if angle <0 and radius < 0, the turtle moves backward and turns counter-clockwise.
Parameters:
  • radius – radius of the arc
  • angle – how many degrees the turtle will move
easygraphics.turtle.move_ellipse(radius_left: float, radius_top: float, angle: float = 360)

Move the turtle in an elliptical path.

“radius_left” is the radius of the ellipse on the direction perpendicular to the turtle’s orientation, it can be postive or negtive;”radius_top” is the radius of the ellipse on the direction parallel to the turtle’s orientation, it must be postive.

The center is radius_left units left of the turtle. That is, if radius_left > 0, the center is on the left of the turtle; if radius_left < 0, the center is on the right of the turtle.

If angle > 0, the turtle moves forward around the center; if angle < 0, the turtle moves backward around the center. So:

  • if angle > 0 and radius_left > 0, the turtle moves forward and turns counter-clockwise;
  • if angle > 0 and radius_left < 0, the turtle move forward and turns clockwise;
  • if angle <0 and radius_left > 0, the turtle moves backward and turns clockwise;
  • if angle <0 and radius_left < 0, the turtle moves backward and turns counter-clockwise.
Parameters:
  • radius_left – the radius of the ellipse on the direction perpendicular to the turtle’s orientation
  • radius_top – the radius of the ellipse on the direction parallel to the turtle’s orientation
  • angle – how many degrees the turtle will move
easygraphics.turtle.get_y() → float

Get the turtle’s current y position.

Returns:the turtle’s y position.
easygraphics.turtle.get_x() → float

Get the turtle’s current x position.

Returns:the turtle’s x position.
easygraphics.turtle.get_heading() → float

Get the turtle’s heading angle.

Returns:the turtle’s heading angle.
easygraphics.turtle.get_turtle() → easygraphics.turtle.turleclass.Turtle

Get the current turtle.

Returns:the current turtle
easygraphics.turtle.get_turtle_world() → easygraphics.turtle.turleclass.TurtleWorld

Get the current turtle world.

Returns:the current turtle world
easygraphics.turtle.set_pen_size(width: float, image: easygraphics.image.Image = None)

Set line width (thickness) of the specified image.

It will be used when drawing lines or shape outlines

Parameters:
  • width – line width (line thickness)
  • image – the target image whose line width is to be set. None means it is the target image (see set_target() and get_target())
easygraphics.turtle.set_immediate(immediate: bool)

Set if there are animations when the turtle moving.

Parameters:immediate – True to turn off animation (the move finishes immediately). False to turn on.
easygraphics.turtle.set_speed(speed)

Set moving speed of the turtle.

Parameters:speed – the new speed
easygraphics.turtle.pen_down()

Pull the pen down – drawing when the turtle moving.

easygraphics.turtle.pen_up()

Pull the pen up – no drawing when the turtle moving.

easygraphics.turtle.pu()

Pull the pen up – no drawing when the turtle moving.

easygraphics.turtle.pd()

Pull the pen down – drawing when the turtle moving.

easygraphics.turtle.hide()

Hide the turtle.

easygraphics.turtle.show()

Show the turtle.

easygraphics.turtle.pause()

Pause the program and wait for mouse clicking or keyboard hitting.

>>> from easygraphics import *
>>> init_graph(800,600)
>>> pause()
>>> close_graph()
easygraphics.turtle.is_run() → bool

Test if the graphics system is running.

Returns:True if the graphics system is running.
easygraphics.turtle.is_out_of_window() → bool

Test if the turtle is out of the graphics window.

Returns:True if the turtle is out of the window, False otherwise.
class easygraphics.turtle.Turtle(world: easygraphics.turtle.turleclass.TurtleWorld)

The Turtle class.

BASE_STEP = 1
DEFAULT_ORENTATION = 90
back(distance: float)

Move the turtle backward by the specified distance, in the direction the turtle is heading.

Parameters:distance – the distance to move
backward(distance: float)

Move the turtle backward by the specified distance, in the direction the turtle is heading.

Parameters:distance – the distance to move
begin_fill()

Begin to record the turtle’s shape drawing path for filling.

bk(distance: float)

Move the turtle backward by the specified distance, in the direction the turtle is heading.

Parameters:distance – the distance to move
cancle_fill()

Cancle the turtle’s drawing path recording.

close()

Close and cleanup the turtle.

static create_turtle_icon() → easygraphics.image.Image

Create the default turtle icon.

Returns:the turtle icon image
end_fill()

Fill the shape enclosed by the turtle’s drawing path after the last call to begin_fill.

facing(x, y)

Turn the turtle to face the point(x,y).

Parameters:
  • x – x coordinate value of the point facing to
  • y – y coordinate value of the point facing to
fd(distance: float)

Move the turtle forward by the specified distance, in the direction the turtle is heading.

Parameters:distance – the distance to move
forward(distance: float)

Move the turtle forward by the specified distance, in the direction the turtle is heading.

Parameters:distance – the distance to move
get_heading() → float

Get the turtle’s heading angle.

Returns:the turtle’s heading angle.
get_icon() → easygraphics.image.Image

Get the icon image of the turtle.

Returns:the icon image
get_x() → float

Get the turtle’s current x position.

Returns:the turtle’s x position.
get_y() → float

Get the turtle’s current y position.

Returns:the turtle’s y position.
gotoxy(x, y)

Move the turtle to point (x,y). Will leave traces if the pen is down.

Parameters:
  • x – x coordinate value of the destination point.
  • y – x coordinate value of the destination point.
hide()

Hide the turtle.

home()

Move the turtle back to the origin(0,0), and heading up. Will leave traces if the pen is down.

is_filling() → bool

Test if it is recording the turtle’s drawing path (for fill).

Returns:
is_out_of_window() → bool

Test if the turtle is out of the graphics window.

Returns:True if the turtle is out of the window, False otherwise.
is_show()

Check if the turtle is shown.

Returns:True the turtle is shown, False the turtle is hiding.
left(degree: float)

Turn turtle left (counter-clockwise) by “degree” degree.

Parameters:degree – the degree to turn
left_turn(degree: float)

Turn turtle left (counter-clockwise) by “degree” degree.

Parameters:degree – the degree to turn
lt(degree: float)

Turn turtle left (counter-clockwise) by “degree” degree.

Parameters:degree – the degree to turn
move_arc(radius: float, angle: float = 360)

Move the turtle in a arc path.

The center is radius units left of the turtle. That is, if radius > 0, the center is on the left of the turtle; if radius < 0, the center is on the right of the turtle.

If angle > 0, the turtle moves forward around the center; if angle < 0, the turtle moves backward around the center. So:

  • if angle > 0 and radius > 0, the turtle moves forward and turns counter-clockwise;
  • if angle > 0 and raidus < 0, the turtle move forward and turns clockwise;
  • if angle <0 and radius > 0, the turtle moves backward and turns clockwise;
  • if angle <0 and radius < 0, the turtle moves backward and turns counter-clockwise.
Parameters:
  • radius – radius of the arc
  • angle – how many degrees the turtle will move
move_ellipse(radius_left: float, radius_top: float, angle: float = 360)

Move the turtle in an elliptical path.

“radius_left” is the radius of the ellipse on the direction perpendicular to the turtle’s orientation, it can be postive or negtive;”radius_top” is the radius of the ellipse on the direction parallel to the turtle’s orientation, it must be postive.

The center is radius_left units left of the turtle. That is, if radius_left > 0, the center is on the left of the turtle; if radius_left < 0, the center is on the right of the turtle.

If angle > 0, the turtle moves forward around the center; if angle < 0, the turtle moves backward around the center. So:

  • if angle > 0 and radius_left > 0, the turtle moves forward and turns counter-clockwise;
  • if angle > 0 and radius_left < 0, the turtle move forward and turns clockwise;
  • if angle <0 and radius_left > 0, the turtle moves backward and turns clockwise;
  • if angle <0 and radius_left < 0, the turtle moves backward and turns counter-clockwise.
Parameters:
  • radius_left – the radius of the ellipse on the direction perpendicular to the turtle’s orientation
  • radius_top – the radius of the ellipse on the direction parallel to the turtle’s orientation
  • angle – how many degrees the turtle will move
pd()

Pull the pen down – drawing when the turtle moving.

pen_down()

Pull the pen down – drawing when the turtle moving.

pen_up()

Pull the pen up – no drawing when the turtle moving.

pu()

Pull the pen up – no drawing when the turtle moving.

reset()

Reset the turtle’s state

right(degree: float)

Turn turtle right (clockwise) by “degree” degree.

Parameters:degree – the degree to turn
right_turn(degree: float)

Turn turtle right (clockwise) by “degree” degree.

Parameters:degree – the degree to turn
rt(degree: float)

Turn turtle right (clockwise) by “degree” degree.

Parameters:degree – the degree to turn
set_heading(angle)

Set the angle current heading to the specified angle.

Parameters:angle – the new heading angle (in degrees).
set_speed(speed: int)

Set moving speed of the turtle.

Parameters:speed – the new speed
setxy(x, y)

Set the turtle’s current position to point (x,y). Will not leave traces.

Parameters:
  • x – x coordinate value of the destination point.
  • y – y coordinate value of the destination point.
show()

Show the turtle.

turn_to(angle)

Turn the angle to orient to the specified angle.

Parameters:angle – the new heading angle (in degrees).
class easygraphics.turtle.TurtleWorld(canvas: Optional[easygraphics.image.Image] = None)

Turtles move and draw in a world. This is the class representing the world.

You must remember to close it by calling the close() method, if you have finished the drawing and won’t use it anymore.

Note that in the default world, we are using a normal coordinate system that (0,0) is in the center of the graphics window (image), the X-axis grows from left to right, and the Y-axis grows from bottom to top. A positive degree means turn counter-clockwise, and a negtive degree means turn clockwise.
add_turtle(turtle: easygraphics.turtle.turleclass.Turtle)

Put the turtle into the world.

Parameters:turtle – the turtle
clear()

Delete all drawings from the screen and reset turtles to its original state.

clear_screen()

Delete all drawings from the screen and reset turtles to its original state.

close()

Close the turtles world.

create_snap_shot() → easygraphics.image.Image

Create a snap shot of the current drawing.

Returns:the snap shot image.
create_turtle()

Create a new turtle in the world and put it to the origin(0,0).

If x and y are None, the turtle is put on the center.

Returns:the created turtle.
cs()

Delete all drawings from the screen and reset turtles to its original state.

get_height() → float

Get the height of the underlying graphics window (image).

Returns:height of the underlying graphics window (image)
get_width() → float

Get the width of the underlying graphics window (image).

Returns:width of the underlying graphics window (image)
get_world_image()

Return the drawing image of the world.

Returns:the drawing image of the world.
is_immediate() → bool

Check if there are animations when turtles moving.

Returns:True if there aren’t any animations (the move finishes immediately), False otherwise.
is_on_screen() → bool

Test if the underlying image is the graphics window.

Returns:True if the underlying image is the graphics window, False otherwise.
is_running()
set_immediate(immediate: bool)

Set if there are animations when turtles moving.

Parameters:immediate – True to turn off animation (the move finishes immediately). False to turn on.
snap_shot_to_image(image, x=0, y=0)

Create a snap shot to the specified image.

The snap shot will be copied to the image’s (x,y).

Parameters:
  • image – the image to copy the snap shot
  • x – x coordinate value of the target position
  • y – y coordinate value of the target position
easygraphics.turtle.easy_run(main_func: Callable, width=640, height=480)

easygraphics.widget package

The qt widget package.

This package provides two qt widget classes, for embeding easygraphics image or turtle graphics in qt applications:

  • ImageWidget: this class is for embedding easygraphics image in qt applications. No animation support
  • TurtleWidget: this class is for embedding turtle graphics in qt applications. Can run animation code (using run_animated_code() method).
Functions
class easygraphics.widget.ImageWidget(parent=None)
close()
getImage() → easygraphics.image.Image

Get the underlying image object.

Returns:the underlying image object
paintEvent(e: <sphinx.ext.autodoc.importer._MockObject object at 0x7f507883c510>)
setImage(image: easygraphics.image.Image)

Set the widget’s underlying Image object.

Parameters:image – the underlying image object
class easygraphics.widget.TurtleWidget(parent=None, width=600, height=400)
close()

Close the widget.

closeEvent(e: <sphinx.ext.autodoc.importer._MockObject object at 0x7f507866e7d0>)
getTurtle() → easygraphics.turtle.turleclass.Turtle

Get the turtle.

Returns:the turtle
getWorld() → easygraphics.turtle.turleclass.TurtleWorld

Get the underlying turtle world.

Returns:the turtle world
hideEvent(QHideEvent)
is_run()

Test if the turtle world is running.

Returns:True if is running, False if not.
paintEvent(e: <sphinx.ext.autodoc.importer._MockObject object at 0x7f507866e7d0>)
run_animated_code(f)

Run turtle code.

Parameters:f – the callable object(function or method) to run
showEvent(QShowEvent)

Package Summary

System init and close

close_graph
init_graph

API Details

class easygraphics.Color

These are the predefined Color constants.

BLACK

Black color

BLUE

Blue

BROWN = '#A8A800'

brown

CYAN

cyan

DARK_BLUE

dark blue

DARK_CYAN

dark cyan

DARK_GRAY

Dark Gray color

DARK_GREEN

dark green

DARK_MAGENTA

dark magenta

DARK_RED

dark red

DARK_YELLOW

dark yellow

GREEN

Green

LIGHT_BLUE = 5526780

Light blue

LIGHT_CYAN = 5569788

light cyan

LIGHT_GRAY = 11053224

Light Gray

LIGHT_GREEN = 5569620

Light green

LIGHT_MAGENTA = 16536828

light magenta

LIGHT_RED = 16536660

light red

LIGHT_YELLOW = 16579668

light yellow

MAGENTA = 11010216

magenta

RED

red

TRANSPARENT

Transparent

Values = (<sphinx.ext.autodoc.importer._MockObject object>, <sphinx.ext.autodoc.importer._MockObject object>, <sphinx.ext.autodoc.importer._MockObject object>, <sphinx.ext.autodoc.importer._MockObject object>, <sphinx.ext.autodoc.importer._MockObject object>, 11010216, '#A8A800', 11053224, <sphinx.ext.autodoc.importer._MockObject object>, 5526780, 5569620, 5569788, 16536660, 16536828, <sphinx.ext.autodoc.importer._MockObject object>, <sphinx.ext.autodoc.importer._MockObject object>, 16579668, <sphinx.ext.autodoc.importer._MockObject object>, <sphinx.ext.autodoc.importer._MockObject object>, <sphinx.ext.autodoc.importer._MockObject object>, <sphinx.ext.autodoc.importer._MockObject object>, <sphinx.ext.autodoc.importer._MockObject object>, <sphinx.ext.autodoc.importer._MockObject object>)
WHITE

White

YELLOW

yellow

class easygraphics.FillStyle

These are the fill style used by draw and fill functions.

BKSLASH_FILL

Used by autodoc_mock_imports.

CLOSE_DOT_FILL

Used by autodoc_mock_imports.

HATCH_FILL

Used by autodoc_mock_imports.

LINE_FILL

Fill with horizontal lines.

LTBKSLASH_FILL

File with diagonal lines.

LTSLASH_FILL

Used by autodoc_mock_imports.

NULL_FILL

Not fill at all. For example, draw_circle() will not fill.

SLASH_FILL

File with diagonal lines.

SOLID_FILL

Fill with solid color. see set_fill_color().

WIDE_DOT_FILL

Used by autodoc_mock_imports.

XHATCH_FILL

Used by autodoc_mock_imports.

class easygraphics.LineStyle

These are the line styles that can be drawn. The styles are:

qpen-solid qpen-dash qpen-dot
LineStyle.SOLID_LINE LineStyle.DASH_LINE LineStyle.DOT_LINE
qpen-dashdot qpen-dashdotdot  
LineStyle.DASH_DOT_LINE LineStyle.DASH_DOT_DOT_LINE LineStyle.NO_PEN
DASH_DOT_DOT_LINE

One dash, two dots, one dash, two dots.

DASH_DOT_LINE

Alternate dots and dashes.

DASH_LINE

Dashes separated by a few pixels.

DOT_LINE

Dots separated by a few pixels.

NO_PEN

no line at all. For example, draw_circle fills but does not draw any boundary line.

SOLID_LINE

A plain line

class easygraphics.RenderMode

These are the graphics window render mode.

RENDER_AUTO = 0

The graphics window is updated after each drawn.

RENDER_MANUAL = 1

The graphics window only updated after functions that wait or delay.

class easygraphics.CompositionMode

Defines the modes supported for digital image compositing.

Composition modes are used to specify how the pixels in one image, the source, are merged with the pixel in another image, the destination.

Please note that the bitwise operation modes are not supported for pens and brushes with alpha components.

CLEAR

(Alpha Composition) The pixels in the destination are cleared (set to fully transparent) independent of the source.

CLEAR_DEST

(Raster Op) The pixels in the destination are cleared (set to 0) independent of the source.

COLOR_BURN

(Blend mode) The destination color is darkened to reflect the source color. A white source color leaves the destination color unchanged.

COLOR_DODGE

(Blend mode) The destination color is brightened to reflect the source color. A black source color leaves the destination color unchanged.

DARKEN

(Blend mode) The darker of the source and destination colors is selected.

DESTINATION

(Alpha Composition) The output is the destination pixel. This means that the blending has no effect.

DESTINATION_AT_TOP

(Alpha Composition) The destination pixel is blended on top of the source, with the alpha of the destination pixel is reduced by the alpha of the source pixel.

DESTINATION_IN

(Alpha Composition) The output is the destination, where the alpha is reduced by that of the source.

DESTINATION_OUT

(Alpha Composition) The output is the destination, where the alpha is reduced by the inverse of the source.

DESTINATION_OVER

(Alpha Composition) The alpha of the destination is used to blend it on top of the source pixels.

DIFFERENCE

(Blend mode) Subtracts the darker of the colors from the lighter. Painting with white inverts the destination color, whereas painting with black leaves the destination color unchanged.

EXCLUSION

(Blend mode) Similar to DIFFERENCE, but with a lower contrast. Painting with white inverts the destination color, whereas painting with black leaves the destination color unchanged.

HARD_LIGHT

(Blend mode) Multiplies or screens the colors depending on the source color. A light source color will lighten the destination color, whereas a dark source color will darken the destination color.

LIGHTEN

(Blend mode) The lighter of the source and destination colors is selected.

MULTIPLY

(Blend mode) The output is the source color multiplied by the destination. Multiplying a color with white leaves the color unchanged, while multiplying a color with black produces black.

NOT_DEST

(Raster Op) Does a bitwise operation where the destination pixels are inverted (NOT dst).

NOT_SRC

(Raster Op) Does a bitwise operation where the source pixels are inverted (NOT src).

NOT_SRC_AND_DEST

(Raster Op) Does a bitwise operation where the source is inverted and then AND’ed with the destination ((NOT src) AND dst).

NOT_SRC_AND_NOT_DEST

(Raster Op) Does a bitwise NOR operation on the source and destination pixels ((NOT src) AND (NOT dst)).

NOT_SRC_OR_DEST

(Raster Op) Does a bitwise operation where the source is inverted and then OR’ed with the destination ((NOT src) OR dst).

NOT_SRC_OR_NOT_DEST

(Raster Op) Does a bitwise NAND operation on the source and destination pixels ((NOT src) OR (NOT dst)).

NOT_SRC_XOR_DEST

(Raster Op) Does a bitwise operation where the source pixels are inverted and then XOR’ed with the destination ((NOT src) XOR dst).

OVERLAY

(Blend mode) Multiplies or screens the colors depending on the destination color. The destination color is mixed with the source color to reflect the lightness or darkness of the destination.

Plus

(Blend mode) Both the alpha and color of the source and destination pixels are added together.

SCREEN

(Blend mode) The source and destination colors are inverted and then multiplied. Screening a color with white produces white, whereas screening a color with black leaves the color unchanged.

SET_DEST

(Raster Op) The pixels in the destination are set (set to 1) independent of the source.

SOFT_LIGHT

(Blend mode) Darkens or lightens the colors depending on the source color. Similar to HARD_LIGHT.

SOURCE

(Alpha Composition) The output is the source pixel.

SOURCE_AT_TOP

(Alpha Composition) The source pixel is blended on top of the destination, with the alpha of the source pixel reduced by the alpha of the destination pixel.

SOURCE_IN

(Alpha Composition) The output is the source, where the alpha is reduced by that of the destination.

SOURCE_OUT

(Alpha Composition) The output is the source, where the alpha is reduced by the inverse of destination.

SOURCE_OVER

(Alpha Composition) This is the default mode. The alpha of the source is used to blend the pixel on top of the destination.

SRC_AND_DEST

(Raster Op) Does a bitwise AND operation on the source and destination pixels (src AND dst).

SRC_AND_NOT_DEST

(Raster Op) Does a bitwise operation where the source is AND’ed with the inverted destination pixels (src AND (NOT dst)).

SRC_OR_DEST

(Raster Op) Does a bitwise OR operation on the source and destination pixels (src OR dst).

SRC_OR_NOT_DEST

(Raster Op) Does a bitwise operation where the source is OR’ed with the inverted destination pixels (src OR (NOT dst)).

SRC_XOR_DEST

(Raster Op) Does a bitwise XOR operation on the source and destination pixels (src XOR dst).

XOR

(Alpha Composition) The source, whose alpha is reduced with the inverse of the destination alpha, is merged with the destination, whose alpha is reduced by the inverse of the source alpha. CompositionMode_Xor is not the same as the bitwise Xor.

class easygraphics.TextFlags

These are the text drawing flags.

ALIGN_BOTTOM

Aligns with the bottom.

ALIGN_CENTER

Centers in both dimensions.

ALIGN_HCENTER

Centers horizontally in the available space.

ALIGN_JUSTIFY

Justifies the text in the available space.

ALIGN_LEFT

Aligns with the left edge.

ALIGN_RIGHT

Aligns with the right edge.

ALIGN_TOP

Aligns with the top.

ALIGN_VCENTER

Centers vertically in the available space.

TEXT_DONT_CLIP

If it’s impossible to stay within the given bounds, it prints outside.

TEXT_EXPAND_TABS

Makes the U+0009 (ASCII tab) character move to the next tab stop.

TEXT_SINGLE_LINE

Treats all whitespace as spaces and prints just one line.

TEXT_WORD_WRAP

Breaks lines at appropriate points, e.g. at word boundaries.

class easygraphics.MouseMessageType

These are the mouse message types.

DOUBLE_CLICK_MESSAGE = 3
NO_MESSAGE = 0
PRESS_MESSAGE = 1
RELEASE_MESSAGE = 2
class easygraphics.FillRule

The Rule for fill polygons.

ODD_EVEN_FILL

Specifies that the region is filled using the odd even fill rule.

WINDING_FILL

Specifies that the region is filled using the non zero winding rule.

class easygraphics.ShapeMode

This flag controls how shapes will be drawn. The framework’s default value is RADIUS.

CENTER = 2
CORNER = 1
CORNERS = 0
RADIUS = 3
class easygraphics.VertexType

These are the type of shape defined by a vertex list.

LINES = 2
POINTS = 1
POLY_LINE = 0
QUADS = 6
QUAD_STRIP = 7
TRIANGLES = 3
TRIANGLE_FAN = 4
TRIANGLE_STRIP = 5
easygraphics.set_line_style(line_style, image: easygraphics.image.Image = None)

Set line style of the specified image.

The line style will be used when drawing lines and shape outlines. Possible value is one of the consts defined in LineStyle.

Parameters:
  • line_style – line style
  • image – the target image whose line style is to be set. None means it is the default target image (see set_target() and get_target())
easygraphics.get_line_style(image: easygraphics.image.Image = None) → int

Get line style of the specified image.

The line style will be used when drawing lines or shape outlines.

Parameters:image – the target image whose line style is to be gotten. None means it is the target image (see set_target() and get_target())
Returns:line style used by the specified image
easygraphics.set_line_width(width: float, image: easygraphics.image.Image = None)

Set line width (thickness) of the specified image.

It will be used when drawing lines or shape outlines

Parameters:
  • width – line width (line thickness)
  • image – the target image whose line width is to be set. None means it is the target image (see set_target() and get_target())
easygraphics.get_line_width(image: easygraphics.image.Image = None) → float

Get line width (thinkness) of the specified image.

It will be used when drawing lines or shape outlines

Parameters:image – the target image whose line width is to be gotten. None means it is the target image (see set_target() and get_target())
Returns:line width (line thickness) of the specified image
easygraphics.get_color(image: easygraphics.image.Image = None) → <sphinx.ext.autodoc.importer._MockObject object at 0x7f50882d5150>

Get the foreground (drawing) color of the specified image.

it will be used when drawing lines or shape outlines

Parameters:image – the target image whose foreground color is to be gotten. None means it is the target image (see set_target() and get_target()).
Returns:foreground color of the specified image
easygraphics.set_color(color, image: easygraphics.image.Image = None)

Set the foreground (drawing) color of the specified image.

it will be used when drawing lines or shape outlines.

the possible color could be consts defined in Color class, or the color created by rgb() function, or PyQt5’s QColor , QGradient object or Qt.GlobalColor consts (see the pyqt reference).

Parameters:
  • color – the foreground color
  • image – the target image whose foreground color is to be set. None means it is the target image (see set_target() and get_target()).
easygraphics.get_fill_color(image: easygraphics.image.Image = None) → <sphinx.ext.autodoc.importer._MockObject object at 0x7f50882d5150>

Get the fill color of the specified image.

it will be used when drawing and fill shapes.

Parameters:image – the target image whose fill color is to be gotten. None means it is the target image (see set_target() and get_target()).
Returns:fill color of the specified image
easygraphics.set_fill_color(color, image: easygraphics.image.Image = None)

Set the fill (drawing) color of the specified image.

It will be used when drawing and fill shapes.

the possible color could be consts defined in Color class, or the color created by rgb() function, or PyQt5’s QColor , QGradient object or Qt.GlobalColor consts (see the pyqt reference).

Parameters:
  • color – the fill color
  • image – the target image whose fill color is to be set. None means it is the target image (see set_target() and get_target()).
easygraphics.get_fill_style(image: easygraphics.image.Image = None) → int

Get fill style of the specified image.

it will be used when drawing and fill shapes.

Parameters:image – the target image whose fill style is to be gotten. None means it is the target image (see set_target() and get_target()).
Returns:fill style of the specified image
easygraphics.set_fill_style(style, image: easygraphics.image.Image = None)
Set fill style of the specified image.

it will be used when drawing and fill shapes. Valid values are the consts defined in FillStyle

Parameters:
  • style – fill style
  • image – the target image whose fill style is to be set. None means it is the target image (see set_target() and get_target()).
Returns:

easygraphics.get_background_color(image: easygraphics.image.Image = None) → <sphinx.ext.autodoc.importer._MockObject object at 0x7f50882d5150>

Get the background color of the image.

Parameters:image – the target image whose background color is to be gotten. None means it is the target image (see set_target() and get_target()).
Returns:background color of the specified image
easygraphics.set_background_color(color, image: easygraphics.image.Image = None)

Set and change the background color.

the possible color could be consts defined in Color class, or the color created by rgb() function, or PyQt5’s QColor , QGradient object or Qt.GlobalColor consts (see the pyqt reference).

Parameters:
  • color – the background color
  • image – the target image whose background color is to be set. None means it is the target image (see set_target() and get_target()).
easygraphics.set_font(font: <sphinx.ext.autodoc.importer._MockObject object at 0x7f50882d5150>, image: easygraphics.image.Image = None)

Set font of the specified image.

Parameters:
  • font – the font will be used
  • image – the target image whose font is to be set. None means it is the target image (see set_target() and get_target()).
easygraphics.get_font(image: easygraphics.image.Image = None) → <sphinx.ext.autodoc.importer._MockObject object at 0x7f50882d5150>

Get font of the specified image.

Parameters:image – the target image whose font is to be gotten. None means it is the target image (see set_target() and get_target()).
Returns:the font used by the specified image
easygraphics.set_font_size(size: int, image: easygraphics.image.Image = None)

Set font size of the specified image.

Parameters:
  • size – font size of the specified image
  • image – the target image whose write mode is to be gotten. None means it is the target image (see set_target() and get_target()).
easygraphics.get_font_size(image: easygraphics.image.Image = None) → int

Get font size of the specified image.

Parameters:image – the target image whose write mode is to be gotten. None means it is the target image (see set_target() and get_target()).
Returns:font size of the specified image
easygraphics.set_composition_mode(mode, image: easygraphics.image.Image = None)

Set composition mode of the specified image.

Composition modes are used to specify how the pixels in the source (image/pen/brush), are merged with the pixel in the destination image.

Parameters:
  • mode – composition mode
  • image – the target image whose composition mode is to be set. None means it is the target image (see set_target() and get_target()).
easygraphics.get_composition_mode(image: easygraphics.image.Image = None) → int

Get composition mode of the specified image.

When drawing ,the composition mode will decide how the result pixel color will be computed (using source color and color of the destination)

Parameters:image – the target image whose composition mode is to be gotten. None means it is the target image (see set_target() and get_target()).
Returns:composition mode
easygraphics.get_drawing_x(image: easygraphics.image.Image = None) → float

Get the x coordinate value of the current drawing position (x,y).

Some drawing functions will use the current pos to draw.(see line_to(),line_rel(),move_to(),move_rel()).

Parameters:image – the target image whose drawing pos is to be gotten. None means it is the target image (see set_target() and get_target()).
Returns:the x coordinate value of the current drawing position
easygraphics.get_drawing_y(image: easygraphics.image.Image = None) → float

Get the y coordinate value of the current drawing position (x,y).

Some drawing functions will use the current pos to draw.(see line_to(),line_rel(),move_to(),move_rel()).

Parameters:image – the target image whose drawing pos is to be gotten. None means it is the target image (see set_target() and get_target()).
Returns:the y coordinate value of the current drawing position
easygraphics.set_view_port(left: int, top: int, right: int, bottom: int, clip: bool = True, image: easygraphics.image.Image = None)

Set the view port of the the specified image.

View port is the drawing zone on the image.

>>> from easygraphics import *
>>> init_graph(800,600)
>>> draw_rect(100,100,300,300)
>>> set_view_port(100,100,300,300)
>>> circle(100,100,50)
>>> circle(100,100,100)
>>> circle(100,100,120)
>>> pause()
>>> close_graph()
Parameters:
  • left – left of the view port rectangle
  • top – top of the view port rectangle
  • right – right of the view port rectangle
  • bottom – bottom of the view port rectangle
  • clip – if True, drawings outside the port rectangle will be clipped
  • image – the target image whose view port is to be gotten. None means it is the target image (see set_target() and get_target()).
easygraphics.reset_view_port(image: easygraphics.image.Image = None)

Reset the view port setting.

Parameters:image – the target image whose view port is to be reset. None means it is the target image (see set_target() and get_target()).
easygraphics.set_origin(offset_x: float, offset_y: float, image: easygraphics.image.Image = None)

Translates the coordinate system by the given offset; i.e.the given offset is added to points.

Parameters:
  • offset_x – offset on the x coordinate
  • offset_y – offset on the y coordinate
  • image – the target image to be translated. None means it is the target image (see set_target() and get_target()).
easygraphics.get_fill_rule(image: easygraphics.image.Image = None) → int

Get the fill rule (algorithm) for filling polygons.

Parameters:image – the target image whose fill rule is to be gotten. None means it is the target image (see set_target() and get_target()).
Returns:the rule used for filling polygons
easygraphics.set_fill_rule(rule, image: easygraphics.image.Image = None)

Set the fill rule (algorithm) for filling polygons.

Parameters:
  • rule – the rule to be used for filling polygons
  • image – the target image whose fill rule is to be set. None means it is the target image (see set_target() and get_target()).
Returns:

easygraphics.set_render_mode(mode: int)

Set render mode of the graphics window.

This mode will control how the graphics window is updated.

possible values:

  • RenderMode.RENDER_AUTO (default) update the window immediately after every drawing
  • RenderMode.MANUAL only update the window after pause()/delay()/delay_fps()/delay_jfps() is called.

RenderMode.MANUAL is used for animations

Parameters:mode – render mode
easygraphics.get_render_mode()

Set render mode of the graphics window.

This mode will control how the graphics window is updated. See set_render_mode()

Returns:render mode
easygraphics.get_drawing_pos(image: easygraphics.image.Image = None) -> (<class 'float'>, <class 'float'>)

Get the current drawing position (x,y).

Some drawing functions will use the current pos to draw.(see line_to(),line_rel(),move_to(),move_rel()).

Parameters:image – the target image whose drawing pos is to be gotten. None means it is the target image (see set_target() and get_target()).
Returns:the current drawing position (x,y)
easygraphics.set_clip_rect(left: int, top: int, right: int, bottom: int, image: easygraphics.image.Image = None)

Set the clip rect.

Drawings outside the clip rect will be clipped.

Parameters:
  • left – left of the clip rectangle
  • top – top of the clip rectangle
  • right – right of the clip rectangle
  • bottom – bottom of the clip rectangle
  • image – the target image whose clip rect is to be gotten. None means it is the target image (see set_target() and get_target()).
easygraphics.set_clipping(clipping: bool, image: easygraphics.image.Image = None)

Set clipping.

Use set_clip_rect() to set the clip rectangle.

Parameters:
  • clipping – True will turn on clipping, False will turn off clipping
  • image – the target image whose clip rect is to be disabled. None means it is the target image (see set_target() and get_target()).
easygraphics.set_window(left: int, top: int, width: int, height: int, image: easygraphics.image.Image = None)

Set the logical drawing window.

All your drawing is first drawing on the logical window, then mapping to view port (see set_view_port()). The logical window’s 4 corner points to streched to match the view port.

If your view port is 200x200,and you use set_window(-50,-50,100,100) to get a 100x100 logical window with the left-top corner at (-50,-50) , then the logical window’s left corner (-50,-50) is set to view port’s (0,0), and right-bottom corner (50,50) is set to view port’s right bottom corner (200,200). All logical points is mapping accordingly.

If you just want to transform the drawing, use set_origin()/translate()/rotate()/scale().

The drawing outside the logical window is not clipped. If you want to clip it, use set_clip_rect().

Parameters:
  • left – x pos of the logical window’s left-top corner
  • top – y pos of the logical window’s left-top corner
  • width – width of the logical window
  • height – height of the logical window
  • image – the target image whose logical window is to be set. None means it is the target image (see set_target() and get_target()).
easygraphics.reset_window(image: easygraphics.image.Image = None)

Reset/remove the logical window.

See set_window().

Parameters:image – the target image whose logical window is to be reset. None means it is the target image (see set_target() and get_target()).
easygraphics.translate(offset_x: float, offset_y: float, image: easygraphics.image.Image = None)

Translates the coordinate system by the given offset; i.e.the given offset is added to points.

Parameters:
  • offset_x – offset on the x coordinate
  • offset_y – offset on the y coordinate
  • image – the target image to be translated. None means it is the target image (see set_target() and get_target()).
easygraphics.rotate(degree: float, x: float = 0, y: float = 0, image: easygraphics.image.Image = None)

Rotates the coordinate system around the point (x,y) with the given angle (in degree) clockwise.

Parameters:
  • degree – the rotate angle (in degree)
  • x – the x coordinate of the rotation center
  • y – the y coordinate of the rotation center
  • image – the target image to be rotated. None means it is the target image (see set_target() and get_target()).
easygraphics.scale(sx: float, sy: float, image: easygraphics.image.Image = None)

Scales the coordinate system by (sx, sy).

Parameters:
  • sx – scale factor on x axis.
  • sy – scale factor on y axis.
  • image – the target image to be scaled. None means it is the target image (see set_target() and get_target()).
easygraphics.skew(sh: float, sv: float, x: float = 0, y: float = 0, image: easygraphics.image.Image = None)

Shear (skew) the coordinates around the point (x,y) by sh,sv.

Parameters:
  • sh – shear ratio on the x-axis
  • sv – shear ratio on the y-axis
  • x – the x coordinate of the skew center
  • y – the y coordinate of the skew center
  • image – the target image to be sheared. None means it is the target image (see set_target() and get_target()).
easygraphics.shear(sh: float, sv: float, x: float = 0, y: float = 0, image: easygraphics.image.Image = None)

Shear (skew) the coordinates around the point (x,y) by sh,sv.

Parameters:
  • sh – shear ratio on the x-axis
  • sv – shear ratio on the y-axis
  • x – the x coordinate of the skew center
  • y – the y coordinate of the skew center
  • image – the target image to be sheared. None means it is the target image (see set_target() and get_target()).
easygraphics.set_flip_y(flip_y: bool, image: easygraphics.image.Image = None) → None

Reflect without texts using the x-axis as the axis (image upside down).

Texts will not get flipped.

Don’t translate the origin to other points (but you can translate and then translate back) before drawing any text. Or the text position’s calculation will get wrong! So if you want to set the origin to the image/image’s center, call set_flip_y() after the set_origin() or translate()!

Note: Use this functions instead of the reflect()/flip()/mirror(),if you only want to draw on an ordinary coordinate system with y-axis grows bottom-up.

Parameters:
  • flip_y – True to turn on the flip, False to turn off.
  • image – the target image to be flipped. None means it is the target image (see set_target() and get_target()).
easygraphics.reflect(x: float, y: float, x1: float = 0, y1: float = 0, image: easygraphics.image.Image = None)

Reflect the coordinates against the line passing (x1,y1) and (x,y).

Note that all things will get reflected, including text! If you just want to draw on a normal coordinate system with the y-axis grows bottom up, use set_flip_y().

Parameters:
  • x – x coordinate value
  • y – y coordinate value
  • x1 – the x coordinate of the second point
  • y1 – the y coordinate of the second point
  • image – the target image to be reflected. None means it is the target image (see set_target() and get_target()).
easygraphics.flip(x: float, y: float, x1: float = 0, y1: float = 0, image: easygraphics.image.Image = None)

Reflect the coordinates against the line passing (x1,y1) and (x,y).

Note that all things will get reflected, including text! If you just want to draw on a normal coordinate system with the y-axis grows bottom up, use set_flip_y().

Parameters:
  • x – x coordinate value
  • y – y coordinate value
  • x1 – the x coordinate of the second point
  • y1 – the y coordinate of the second point
  • image – the target image to be reflected. None means it is the target image (see set_target() and get_target()).
easygraphics.mirror(x: float, y: float, x1: float = 0, y1: float = 0, image: easygraphics.image.Image = None)

Reflect the coordinates against the line passing (x1,y1) and (x,y).

Note that all things will get reflected, including text! If you just want to draw on a normal coordinate system with the y-axis grows bottom up, use set_flip_y().

Parameters:
  • x – x coordinate value
  • y – y coordinate value
  • x1 – the x coordinate of the second point
  • y1 – the y coordinate of the second point
  • image – the target image to be reflected. None means it is the target image (see set_target() and get_target()).
easygraphics.reset_transform(image: easygraphics.image.Image = None)

Reset all transforms (translate/rotate/scale).

Parameters:image – the target image to be reset. None means it is the target image (see set_target() and get_target()).
easygraphics.save_settings(image: easygraphics.image.Image = None)

Save current drawing settings.

See restore_settings().

Note: background_color and current position won’t be saved and restored.

Parameters:image – the target image whose drawing settings is to be saved. None means it is the target image (see set_target() and get_target()).
easygraphics.restore_settings(image: easygraphics.image.Image = None)

Restore previously saved drawing settings.

See save_settings().

Note: background_color and current position won’t be saved and restored.

Parameters:image – the target image whose drawing settings is to be restored. None means it is the target image (see set_target() and get_target()).
easygraphics.get_width(image: easygraphics.image.Image = None) → int

Get width of the specified image.

Parameters:image – the target image whose width is to be gotten. None means it is the target image (see set_target() and get_target()).
Returns:width of the specified image
easygraphics.get_height(image: easygraphics.image.Image = None) → int

Get height of the specified image.

Parameters:image – the target image whose width is to be gotten. None means it is the target image (see set_target() and get_target()).
Returns:height of the specified image
easygraphics.get_write_mode(image: easygraphics.image.Image = None) → int

Get composition mode of the specified image.

When drawing ,the composition mode will decide how the result pixel color will be computed (using source color and color of the destination)

Parameters:image – the target image whose composition mode is to be gotten. None means it is the target image (see set_target() and get_target()).
Returns:composition mode
easygraphics.set_write_mode(mode, image: easygraphics.image.Image = None)

Set composition mode of the specified image.

Composition modes are used to specify how the pixels in the source (image/pen/brush), are merged with the pixel in the destination image.

Parameters:
  • mode – composition mode
  • image – the target image whose composition mode is to be set. None means it is the target image (see set_target() and get_target()).
easygraphics.get_transform(image: easygraphics.image.Image = None) → <sphinx.ext.autodoc.importer._MockObject object at 0x7f50882d5150>

Get transform matrix of the image.

Parameters:image – the target image whose transform matrix is to be gotten. None means it is the target image (see set_target() and get_target()).
Returns:the transform matrix
easygraphics.set_transform(transform: <sphinx.ext.autodoc.importer._MockObject object at 0x7f50882d5150>, image: easygraphics.image.Image = None)

Set image’s transform matrix.

Parameters:
  • transform – the transform matrix to set
  • image – the target image whose transform matrix is to be gotten. None means it is the target image (see set_target() and get_target()).
easygraphics.push_transform(image: easygraphics.image.Image = None)

Push (save) the current transform to the transform stack.

easygraphics.pop_transform(image: easygraphics.image.Image = None)

Pop the last saved transform from the transform stack, and use it as the current transform.

easygraphics.set_rect_mode(mode, image: easygraphics.image.Image = None)
easygraphics.get_rect_mode(image: easygraphics.image.Image = None) → int
easygraphics.set_ellipse_mode(mode, image: easygraphics.image.Image = None)
easygraphics.get_ellipse_mode(image: easygraphics.image.Image = None) → int
easygraphics.set_antialiasing(anti: bool = True, image: easygraphics.image.Image = None) → None

Set Anti Aliasing

Parameters:
  • anti – if antialiasing should be set
  • image – the image to set anti aliasing. None means it is the target image (see set_target() and get_target()).
easygraphics.draw_point(x: float, y: float, image: easygraphics.image.Image = None)

Draw a point at (x,y) on the specified image.

Parameters:
  • x – x coordinate value of the drawing point
  • y – y coordinate value of the drawing point
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.put_pixel(x: int, y: int, color, image: easygraphics.image.Image = None)

Set a pixel’s color on the specified image.

Parameters:
  • x – x coordinate value of the pixel
  • y – y coordinate value of the pixel
  • color – the color
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.get_pixel(x: int, y: int, image: easygraphics.image.Image = None) → <sphinx.ext.autodoc.importer._MockObject object at 0x7f50882d5150>

Get a pixel’s color on the specified image.

Parameters:
  • x – x coordinate value of the pixel
  • y – y coordinate value of the pixel
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
Returns:

color of the pixel

easygraphics.line(x1, y1, x2, y2, image: easygraphics.image.Image = None)

Draw a line from (x1,y1) to (x2,y2) on the specified image.

It’s the same with line().

Parameters:
  • x1 – x coordinate value of the start point
  • y1 – y coordinate value of the start point
  • x2 – x coordinate value of the end point
  • y2 – y coordinate value of the start point
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.draw_line(x1, y1, x2, y2, image: easygraphics.image.Image = None)

Draw a line from (x1,y1) to (x2,y2) on the specified image.

It’s the same with line().

Parameters:
  • x1 – x coordinate value of the start point
  • y1 – y coordinate value of the start point
  • x2 – x coordinate value of the end point
  • y2 – y coordinate value of the start point
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.move_to(x: float, y: float, image: easygraphics.image.Image = None)

Set the drawing position to (x,y).

The drawing position is used by line_to(), line_rel() and move_rel().

Parameters:
  • x – x coordinate value of the new drawing position
  • y – y coordinate value of the new drawing position
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.move_rel(dx: float, dy: float, image: easygraphics.image.Image = None)

Move the drawing position by (dx,dy).

If the old position is (x,y), then the new position will be (x+dx,y+dy).

The drawing position is used by line_to(), line_rel().

Parameters:
  • dx – x coordinate offset of the new drawing position
  • dy – y coordinate offset of the new drawing position
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.line_to(x: float, y: float, image: easygraphics.image.Image = None)

Draw a line from the current drawing position to (x,y), then set the drawing position is set to (x,y).

Parameters:
  • x – x coordinate value of the new drawing position
  • y – y coordinate value of the new drawing position
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.line_rel(dx: float, dy: float, image: easygraphics.image.Image = None)

Draw a line from the current drawing position (x,y) to (x+dx,y+dy), then set the drawing position is set to (x+dx,y+dy).

Parameters:
  • dx – x coordinate offset of the new drawing position
  • dy – y coordinate offset of the new drawing position
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.circle(x: float, y: float, r: float, image: easygraphics.image.Image = None)

Draw a circle outline centered at (x,y) with radius r.

The circle is not filled.

Parameters:
  • x – x coordinate value of the circle’s center
  • y – y coordinate value of the circle’s center
  • r – radius of the circle
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.draw_circle(x: float, y: float, r: float, image: easygraphics.image.Image = None)

Draw a circle centered at (x,y) with radius r.

The circle is filled and has outline.

Parameters:
  • x – x coordinate value of the circle’s center
  • y – y coordinate value of the circle’s center
  • r – radius of the circle
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.fill_circle(x: float, y: float, r: float, image: easygraphics.image.Image = None)

Fill a circle centered at (x,y) with radius r.

The circle doesn’t has outline.

Parameters:
  • x – x coordinate value of the circle’s center
  • y – y coordinate value of the circle’s center
  • r – radius of the circle
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.ellipse(x, y, radius_x, radius_y, image: easygraphics.image.Image = None)

Draw an ellipse outline centered at (x,y) , radius on x-axis is radius_x, radius on y-axis is radius_y.

The ellipse is not filled.

Parameters:
  • x – x coordinate value of the ellipse’s center
  • y – y coordinate value of the ellipse’s center
  • radius_x – radius on x-axis of the ellipse
  • radius_y – radius on y-axis of the ellipse
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.draw_ellipse(x, y, radius_x, radius_y, image: easygraphics.image.Image = None)

Draw an ellipse centered at (x,y) , radius on x-axis is radius_x, radius on y-axis is radius_y.

The ellipse is filled and has outline.

Parameters:
  • x – x coordinate value of the ellipse’s center
  • y – y coordinate value of the ellipse’s center
  • radius_x – radius on x-axis of the ellipse
  • radius_y – radius on y-axis of the ellipse
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.fill_ellipse(x, y, radius_x, radius_y, image: easygraphics.image.Image = None)

Fill an ellipse centered at (x,y) , radius on x-axis is radius_x, radius on y-axis is radius_y.

The ellipse doesn’t has outline.

Parameters:
  • x – x coordinate value of the ellipse’s center
  • y – y coordinate value of the ellipse’s center
  • radius_x – radius on x-axis of the ellipse
  • radius_y – radius on y-axis of the ellipse
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.arc(x: float, y: float, start_angle: float, end_angle: float, radius_x: float, radius_y: float, image: easygraphics.image.Image = None)

Draw an elliptical arc from start_angle to end_angle. The base ellipse is centered at (x,y) which radius on x-axis is radius_x and radius on y-axis is radius_y.

Note: Positive values for the angles mean counter-clockwise while negative values mean the clockwise direction. Zero degrees is at the 3 o’clock position.
Parameters:
  • x – x coordinate value of the ellipse’s center
  • y – y coordinate value of the ellipse’s center
  • start_angle – start angle of the arc
  • end_angle – end angle of the arc
  • radius_x – radius on x-axis of the ellipse
  • radius_y – radius on y-axis of the ellipse
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.draw_arc(x: float, y: float, start_angle: float, end_angle: float, radius_x: float, radius_y: float, image: easygraphics.image.Image = None)

Draw an elliptical arc from start_angle to end_angle. The base ellipse is centered at (x,y) which radius on x-axis is radius_x and radius on y-axis is radius_y.

Note: Positive values for the angles mean counter-clockwise while negative values mean the clockwise direction. Zero degrees is at the 3 o’clock position.
Parameters:
  • x – x coordinate value of the ellipse’s center
  • y – y coordinate value of the ellipse’s center
  • start_angle – start angle of the arc
  • end_angle – end angle of the arc
  • radius_x – radius on x-axis of the ellipse
  • radius_y – radius on y-axis of the ellipse
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.pie(x: float, y: float, start_angle: float, end_angle: float, radius_x: float, radius_y: float, image: easygraphics.image.Image = None)

Draw an elliptical pie outline from start_angle to end_angle. The base ellipse is centered at (x,y) which radius on x-axis is radius_x and radius on y-axis is radius_y.

The pie is not filled.

Note: Positive values for the angles mean counter-clockwise while negative values mean the clockwise direction. Zero degrees is at the 3 o’clock position.
Parameters:
  • x – x coordinate value of the ellipse’s center
  • y – y coordinate value of the ellipse’s center
  • start_angle – start angle of the pie
  • end_angle – end angle of the pie
  • radius_x – radius on x-axis of the ellipse
  • radius_y – radius on y-axis of the ellipse
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.draw_pie(x: float, y: float, start_angle: float, end_angle: float, radius_x: float, radius_y: float, image: easygraphics.image.Image = None)

Draw an elliptical pie from start_angle to end_angle. The base ellipse is centered at (x,y) which radius on x-axis is radius_x and radius on y-axis is radius_y.

The pie is filled and has outline.

Note: Positive values for the angles mean counter-clockwise while negative values mean the clockwise direction. Zero degrees is at the 3 o’clock position.
Parameters:
  • x – x coordinate value of the ellipse’s center
  • y – y coordinate value of the ellipse’s center
  • start_angle – start angle of the pie
  • end_angle – end angle of the pie
  • radius_x – radius on x-axis of the ellipse
  • radius_y – radius on y-axis of the ellipse
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.fill_pie(x: float, y: float, start_angle: float, end_angle: float, radius_x: float, radius_y: float, image: easygraphics.image.Image = None)

Fill an elliptical pie from start_angle to end_angle. The base ellipse is centered at (x,y) which radius on x-axis is radius_x and radius on y-axis is radius_y.

The pie doesn’t have outline.

Note: Positive values for the angles mean counter-clockwise while negative values mean the clockwise direction. Zero degrees is at the 3 o’clock position.
Parameters:
  • x – x coordinate value of the ellipse’s center
  • y – y coordinate value of the ellipse’s center
  • start_angle – start angle of the pie
  • end_angle – end angle of the pie
  • radius_x – radius on x-axis of the ellipse
  • radius_y – radius on y-axis of the ellipse
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.chord(x: float, y: float, start_angle: float, end_angle: float, radius_x: float, radius_y: float, image: easygraphics.image.Image = None)

Draw an elliptical chord outline from start_angle to end_angle. The base ellipse is centered at (x,y) which radius on x-axis is radius_x and radius on y-axis is radius_y.

The chord is not filled.

Note: Positive values for the angles mean counter-clockwise while negative values mean the clockwise direction. Zero degrees is at the 3 o’clock position.
Parameters:
  • x – x coordinate value of the ellipse’s center
  • y – y coordinate value of the ellipse’s center
  • start_angle – start angle of the chord
  • end_angle – end angle of the chord
  • radius_x – radius on x-axis of the ellipse
  • radius_y – radius on y-axis of the ellipse
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.draw_chord(x: float, y: float, start_angle: float, end_angle: float, radius_x: float, radius_y: float, image: easygraphics.image.Image = None)

Draw an elliptical chord outline from start_angle to end_angle. The base ellipse is centered at (x,y) which radius on x-axis is radius_x and radius on y-axis is radius_y.

The chord is filled and has outline

Note: Positive values for the angles mean counter-clockwise while negative values mean the clockwise direction. Zero degrees is at the 3 o’clock position.
Parameters:
  • x – x coordinate value of the ellipse’s center
  • y – y coordinate value of the ellipse’s center
  • start_angle – start angle of the chord
  • end_angle – end angle of the chord
  • radius_x – radius on x-axis of the ellipse
  • radius_y – radius on y-axis of the ellipse
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.fill_chord(x: float, y: float, start_angle: float, end_angle: float, radius_x: float, radius_y: float, image: easygraphics.image.Image = None)

Draw an elliptical chord outline from start_angle to end_angle. The base ellipse is centered at (x,y) which radius on x-axis is radius_x and radius on y-axis is radius_y.

The chord doesn’t have outline.

Note: Positive values for the angles mean counter-clockwise while negative values mean the clockwise direction. Zero degrees is at the 3 o’clock position.
Parameters:
  • x – x coordinate value of the ellipse’s center
  • y – y coordinate value of the ellipse’s center
  • start_angle – start angle of the chord
  • end_angle – end angle of the chord
  • radius_x – radius on x-axis of the ellipse
  • radius_y – radius on y-axis of the ellipse
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.bezier(x0: float, y0: float, x1: float, y1: float, x2: float, y2: float, x3: float, y3: float, image: easygraphics.image.Image = None)

Draw a cubic bezier curve.

points (x0,y0),(x1,y1),(x2,y2),(x3,y3) are the control points of the curve,

>>> from easygraphics import *
>>> init_graph(600,400)
>>> points=[300,50,200,50,200,200,100,200]
>>> draw_bezier(*points)
>>> pause()
>>> close_graph()
Parameters:
  • x0 – x coordinate of the first control point
  • y0 – y coordinate of the first control point
  • x1 – x coordinate of the second control point
  • y1 – y coordinate of the second control point
  • x2 – x coordinate of the third control point
  • y2 – y coordinate of the third control point
  • x3 – x coordinate of the fourth control point
  • y3 – y coordinate of the fourth control point
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.draw_bezier(x0: float, y0: float, x1: float, y1: float, x2: float, y2: float, x3: float, y3: float, image: easygraphics.image.Image = None)

Draw a cubic bezier curve.

points (x0,y0),(x1,y1),(x2,y2),(x3,y3) are the control points of the curve,

>>> from easygraphics import *
>>> init_graph(600,400)
>>> points=[300,50,200,50,200,200,100,200]
>>> draw_bezier(*points)
>>> pause()
>>> close_graph()
Parameters:
  • x0 – x coordinate of the first control point
  • y0 – y coordinate of the first control point
  • x1 – x coordinate of the second control point
  • y1 – y coordinate of the second control point
  • x2 – x coordinate of the third control point
  • y2 – y coordinate of the third control point
  • x3 – x coordinate of the fourth control point
  • y3 – y coordinate of the fourth control point
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.lines(*points, image: easygraphics.image.Image = None)

Draw lines.

“points” is a 2D point pair list. It should contain even number of points, and each 2 points make a point pair. And each point have 2 coordinate values(x,y). So if you have n point pairs, the points list should have 4*n values.

For examples , if points is [50,50,550,350, 50,150,550,450, 50,250,550,550], draw_lines() will draw 3 lines: (50,50) to (550,350), (50,150) to (550,450), (50,250) to (550,550)

>>> from easygraphics import *
>>> init_graph(600,600)
>>> draw_lines(50, 50, 550, 350, 50, 150, 550, 450, 50, 250, 550, 550)
>>> pause()
>>> close_graph()
Parameters:
  • points – point value list
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.draw_lines(*points, image: easygraphics.image.Image = None)

Draw lines.

“points” is a 2D point pair list. It should contain even number of points, and each 2 points make a point pair. And each point have 2 coordinate values(x,y). So if you have n point pairs, the points list should have 4*n values.

For examples , if points is [50,50,550,350, 50,150,550,450, 50,250,550,550], draw_lines() will draw 3 lines: (50,50) to (550,350), (50,150) to (550,450), (50,250) to (550,550)

>>> from easygraphics import *
>>> init_graph(600,600)
>>> draw_lines(50, 50, 550, 350, 50, 150, 550, 450, 50, 250, 550, 550)
>>> pause()
>>> close_graph()
Parameters:
  • points – point value list
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.poly_line(*end_points, image: easygraphics.image.Image = None)

Draw a poly line.

“end_points” is a 2D points list. Each 2 values in the list make a point. A poly line will be drawn to connect adjacent end_points defined by the the list.

For examples , if “end_points” is [50,50,550,350, 50,150,550,450, 50,250,550,550], draw_poly_line() will draw 5 lines: (50,50) to (550,350), (550,350) to (50,150), (50,150) to (550,450), (550,540) to (50,250) and(50,250) to (550,550).

>>> from easygraphics import *
>>> init_graph(600,600)
>>> draw_poly_line(50,50,550,350,50,150,550,450,50,250,550,550)
>>> pause()
>>> close_graph()
Parameters:
  • end_points – point value list
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.draw_poly_line(*end_points, image: easygraphics.image.Image = None)

Draw a poly line.

“end_points” is a 2D points list. Each 2 values in the list make a point. A poly line will be drawn to connect adjacent end_points defined by the the list.

For examples , if “end_points” is [50,50,550,350, 50,150,550,450, 50,250,550,550], draw_poly_line() will draw 5 lines: (50,50) to (550,350), (550,350) to (50,150), (50,150) to (550,450), (550,540) to (50,250) and(50,250) to (550,550).

>>> from easygraphics import *
>>> init_graph(600,600)
>>> draw_poly_line(50,50,550,350,50,150,550,450,50,250,550,550)
>>> pause()
>>> close_graph()
Parameters:
  • end_points – point value list
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.polygon(*vertices, image: easygraphics.image.Image = None)

Draw polygon outline.

“vertices” is a 2D point list. Each 2 values in the list make a point. A polygon will be drawn to connect adjacent points defined by the the list.

For examples , if “vertices” is [50,50,550,350, 50,150], polygon() will draw a triangle with vertices at (50,50) , (550,350) and (50,150).

The polygon is not filled.

>>> from easygraphics import *
>>> init_graph(600,600)
>>> set_color(Color.RED)
>>> polygon(50,50,550,350,50,150)
>>> pause()
>>> close_graph()
Parameters:
  • vertices – point value list
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.draw_polygon(*vertices, image: easygraphics.image.Image = None)

Draw a polygon.

“vertices” is a 2D point list. Each 2 values in the list make a point. A polygon will be drawn to connect adjacent points defined by the the list.

For examples , if “vertices” is [50,50,550,350, 50,150], draw_polygon() will draw a triangle with vertices at (50,50) , (550,350) and (50,150)

The polygon is filled and has outline.

>>> from easygraphics import *
>>> init_graph(600,600)
>>> set_color(Color.RED)
>>> set_fill_color(Color.LIGHT_MAGENTA)
>>> draw_polygon(50,50,550,350,50,150)
>>> pause()
>>> close_graph()
Parameters:
  • vertices – point value list
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.fill_polygon(*vertices, image: easygraphics.image.Image = None)

Fill a polygon.

“vertices” is a 2D point list. Each 2 values in the list make a point. A polygon will be drawn to connect adjacent points defined by the the list.

For examples , if “vertices” is [50,50,550,350, 50,150], fill_polygon() will fill a triangle with vertices at (50,50) , (550,350) and (50,150).

The polygon doesn’t have outline.

>>> from easygraphics import *
>>> init_graph(600,600)
>>> set_fill_color(Color.LIGHT_MAGENTA)
>>> fill_polygon(50,50,550,350,50,150)
>>> pause()
>>> close_graph()
Parameters:
  • vertices – point value list
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.rect(left: float, top: float, right: float, bottom: float, image: easygraphics.image.Image = None)

Draws a rectangle outline with upper left corner at (left, top) and lower right corner at (right,bottom).

The rectangle is not filled.

Parameters:
  • left – x coordinate value of the upper left corner
  • top – y coordinate value of the upper left corner
  • right – x coordinate value of the lower right corner
  • bottom – y coordinate value of the lower right corner
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.draw_rect(left: float, top: float, right: float, bottom: float, image: easygraphics.image.Image = None)

Draws a rectangle with upper left corner at (left, top) and lower right corner at (right,bottom).

The rectangle is filled and has outline.

Parameters:
  • left – x coordinate value of the upper left corner
  • top – y coordinate value of the upper left corner
  • right – x coordinate value of the lower right corner
  • bottom – y coordinate value of the lower right corner
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.fill_rect(left: float, top: float, right: float, bottom: float, image: easygraphics.image.Image = None)

Draws a rectangle with upper left corner at (left, top) and lower right corner at (right,bottom).

The rectangle doesn’t have outline.

Parameters:
  • left – x coordinate value of the upper left corner
  • top – y coordinate value of the upper left corner
  • right – x coordinate value of the lower right corner
  • bottom – y coordinate value of the lower right corner
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.rounded_rect(left: float, top: float, right: float, bottom: float, round_x: float, round_y: float, image: easygraphics.image.Image = None)

Draws a rounded rectangle outline with upper left corner at (left, top) , lower right corner at (right,bottom). Raidus on x-axis of the corner ellipse arc is round_x, radius on y-axis of the corner ellipse arc is round_y.

The rectangle is not filled.

Parameters:
  • left – x coordinate value of the upper left corner
  • top – y coordinate value of the upper left corner
  • right – x coordinate value of the lower right corner
  • bottom – y coordinate value of the lower right corner
  • round_x – raidus on x-axis of the corner ellipse arc
  • round_y – radius on y-axis of the corner ellipse arc
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.draw_rounded_rect(left: float, top: float, right: float, bottom: float, round_x: float, round_y: float, image: easygraphics.image.Image = None)

Draws a rounded rectangle with upper left corner at (left, top) , lower right corner at (right,bottom). raidus on x-axis of the corner ellipse arc is round_x, radius on y-axis of the corner ellipse arc is round_y.

The rectangle is filled and has outline.

Parameters:
  • left – x coordinate value of the upper left corner
  • top – y coordinate value of the upper left corner
  • right – x coordinate value of the lower right corner
  • bottom – y coordinate value of the lower right corner
  • round_x – raidus on x-axis of the corner ellipse arc
  • round_y – radius on y-axis of the corner ellipse arc
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.fill_rounded_rect(left: float, top: float, right: float, bottom: float, round_x: float, round_y: float, image: easygraphics.image.Image = None)

Fill a rounded rectangle with upper left corner at (left, top) , lower right corner at (right,bottom). raidus on x-axis of the corner ellipse arc is round_x, radius on y-axis of the corner ellipse arc is round_y.

The rectangle doesn’t have outline.

Parameters:
  • left – x coordinate value of the upper left corner
  • top – y coordinate value of the upper left corner
  • right – x coordinate value of the lower right corner
  • bottom – y coordinate value of the lower right corner
  • round_x – raidus on x-axis of the corner ellipse arc
  • round_y – radius on y-axis of the corner ellipse arc
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.flood_fill(x: int, y: int, border_color, image: easygraphics.image.Image = None)

Flood fill the image starting from(x,y) and ending at borders with border_color.

The fill region border must be closed,or the whole image will be filled!

Parameters:
  • x – x coordinate value of the start point
  • y – y coordinate value of the start point
  • border_color – color of the fill region border
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.draw_image(x: int, y: int, src_image: easygraphics.image.Image, width: int = 0, height: int = 0, src_x: int = 0, src_y: int = 0, src_width: int = -1, src_height: int = -1, with_background=True, composition_mode=None, dst_image: easygraphics.image.Image = None)

Copy part of the source image (src_image) to the destination image (dst_image).

(x, y) specifies the top-left point in the destination image that is to be drawn onto.

(width, height) specifies the size of drawing part on the destination image.The default is (0, 0).

(src_x, src_y) specifies the top-left point of the part in the source image that is to be drawn. The default is (0, 0).

(src_width, src_height) specifies the size of the part of the source image that is to be drawn. The default, (0, 0) (and negative) means all the way to the bottom-right of the image.

if with_background is False, the source image’s background will not be copied.

The final result will depend on the composition mode and the source image’s background. In the default mode (CompositionMode.SOURCE_OVER), the transparent background in the source will not overwrite the destination.

param x:x coordinate value of the upper left point on the destination image
param y:y coordinate value of the upper left point on the destination image
param src_image:
 the source image to be copied
param width:width of the drawing part on the destination image
param height:height of the drawing part on the destination image
param src_x:x coordinate value of the top-left point of of the part to be drawn
param src_y:y coordinate value of the top-left point of of the part to be drawn
param src_width:
 witdh of the top-left point of of the part to be drawn
param src_height:
 height of the top-left point of of the part to be drawn
param with_background:
 if the background should be copied.
param composition_mode:
 if is None, use dst image’s composition mode to copy.
param dst_image:
 the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.clear_device(image: easygraphics.image.Image = None)

Clear the image to show the background.

Parameters:image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.clear_view_port(image: easygraphics.image.Image = None)

clear view port to show the background.

Parameters:image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.quadratic(x0: float, y0: float, x1: float, y1: float, x2: float, y2: float, image: easygraphics.image.Image = None)

Draw a quadratic bezier curve.

points (x0,y0),(x1,y1),(x2,y2) are the control points of the curve,

Parameters:
  • x0 – x coordinate of the first control point
  • y0 – y coordinate of the first control point
  • x1 – x coordinate of the second control point
  • y1 – y coordinate of the second control point
  • x2 – x coordinate of the third control point
  • y2 – y coordinate of the third control point
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.draw_quadratic(x0: float, y0: float, x1: float, y1: float, x2: float, y2: float, image: easygraphics.image.Image = None)

Draw a quadratic bezier curve.

points (x0,y0),(x1,y1),(x2,y2) are the control points of the curve,

Parameters:
  • x0 – x coordinate of the first control point
  • y0 – y coordinate of the first control point
  • x1 – x coordinate of the second control point
  • y1 – y coordinate of the second control point
  • x2 – x coordinate of the third control point
  • y2 – y coordinate of the third control point
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.fill_image(color, image: easygraphics.image.Image = None)

Fill the whole image with the specified color.

Parameters:
  • color – the fill color
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.clear(image: easygraphics.image.Image = None)

Clear the image to show the background.

Parameters:image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.draw_curve(*points, image: easygraphics.image.Image = None)

Draw a Catmull-Rom spline.

Parameters:
  • points – control points
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.curve(*points, image: easygraphics.image.Image = None)

Draw a Catmull-Rom spline.

Parameters:
  • points – control points
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.begin_shape(type=0, image: easygraphics.image.Image = None)

Begin a shape definition

Parameters:
  • type – the type of the shape. See VertexType const for more information
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.end_shape(close=False, image: easygraphics.image.Image = None)

End a shape definition

Parameters:
  • close – if the shape should be closed. Only polylines can be closed.
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.vertex(x: float, y: float, image: easygraphics.image.Image = None)

Define a vertex.

Parameters:
  • x – x pos of the vertex
  • y – y pos of the vertex
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.bezier_vertex(x1: float, y1: float, x2: float, y2: float, x3: float, y3: float, image: easygraphics.image.Image = None)

Define a cubic Bezier curve. The first control point of the curve the vertex defined last time.

Parameters:
  • x1 – x pos of the second control point
  • y1 – y pos of the second control point
  • x2 – x pos of the third control point
  • y2 – y pos of the third control point
  • x3 – x pos of the fourth control point
  • y3 – y pos of the fourth control point
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.quadratic_vertex(x1: float, y1: float, x2: float, y2: float, image: easygraphics.image.Image = None)

Define a quadratic Bezier curve vertex. The first control point of the curve the vertex defined last time.

Parameters:
  • x1 – x pos of the second control point
  • y1 – y pos of the second control point
  • x2 – x pos of the third control point
  • y2 – y pos of the third control point
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.curve_vertex(x: float, y: float, image: easygraphics.image.Image = None)

Define a Catmull-Rom curve vertex.

Parameters:
  • x – x pos of the vertex
  • y – y pos of the vertex
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.bezier_point(p0: float, p1: float, p2: float, p3: float, t: float)

Calculate the position of a point with parameter t on the cubic bezier curve.

Note that the parameter t must >=0 and <=1 .

Parameters:
  • p0 – position of the first control point
  • p1 – position of the second control point
  • p2 – position of the third control point
  • p3 – position of the forth control point
  • t – the parameter t
Returns:

position of the point

easygraphics.bezier_tangent(p0: float, p1: float, p2: float, p3: float, t: float)

Calculate the tangent of the point with parameter t on the cubic bezier curve.

Note that the parameter t must >=0 and <=1 .

Parameters:
  • p0 – position of the first control point
  • p1 – position of the second control point
  • p2 – position of the third control point
  • p3 – position of the forth control point
  • t – the parameter t
Returns:

tangent of the point

easygraphics.curve_point(p0: float, p1: float, p2: float, p3: float, t: float)

Calculate the position of the point with parameter t on a Catmull-Rom spline.

Note that the parameter t must >=0 and <=1 .

Parameters:
  • p0 – position of the first control point
  • p1 – position of the second control point
  • p2 – position of the third control point
  • p3 – position of the forth control point
  • t – the parameter t
Returns:

position of the point

easygraphics.curve_tangent(p0: float, p1: float, p2: float, p3: float, t: float)

Calculate the tangent of the point with parameter t on a Catmull-Rom spline.

Note that the parameter t must >=0 and <=1 .

Parameters:
  • p0 – position of the first control point
  • p1 – position of the second control point
  • p2 – position of the third control point
  • p3 – position of the forth control point
  • t – the parameter t
Returns:

tangent of the point

easygraphics.draw_text(x, y, *args, sep=' ', image: easygraphics.image.Image = None)

Prints the given texts beginning at the given position (x,y).

Parameters:
  • x – x coordinate value of the start point
  • y – y coordinate value of the start point
  • args – things to be printed (like print())
  • sep – seperator used to join strings
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.draw_rect_text(x: int, y: int, width: int, height: int, *args, flags=<sphinx.ext.autodoc.importer._MockObject object>, sep: str = ' ', image: easygraphics.image.Image = None)

Print the given texts in the specified rectangle area.

Flags are defined as TextFlag const.

Parameters:
  • x – x coordinate of the output rectangle’s upper left corner
  • y – y coordinate of the output rectangle’s upper left corner
  • width – width of the output rectangle
  • height – height of the output rectangle
  • args – things to be printed (like print())
  • flags – align flags
  • sep – seperator used to join strings
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.text_width(text: str, image: easygraphics.image.Image = None) → int

Return width of the text.

Parameters:
  • text – the text
  • image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
Returns:

width of the text

easygraphics.text_height(image: easygraphics.image.Image = None) → int

Return height of the text (font height).

Parameters:image – the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
Returns:height of the text (font height)
easygraphics.set_target(image: easygraphics.image.Image = None)

Set the target image for drawing on.

Parameters:image – the target image which will be painted on. None means paint on the graphics window.
easygraphics.get_target() → Optional[easygraphics.image.Image]

Get the target image for drawing on.

Returns:the target image which will be painted on. None means paint on the graphics window.
easygraphics.create_image(width, height) → easygraphics.image.Image

Create a new image.

Parameters:
  • width – width of the new image
  • height – height of the new image
Returns:

the created image

easygraphics.create_image_from_ndarray(array) → easygraphics.image.Image

Convert a ndarray (opencv 3.0 image) to an Image object

easygraphics.save_image(filename: str, with_background=True, image: easygraphics.image.Image = None)

Save image to file.

Set with_background to False to get a transparent background image.

Note that JPEG format doesn’t support transparent. Use PNG format if you want a transparent background.

Parameters:
  • filename – path of the file
  • with_background – True to save the background together. False not
  • image – the target image which will be saved. None means it is the target image (see set_target() and get_target()).
easygraphics.close_image(image: easygraphics.image.Image)

Close and clean up the specified image.

Parameters:image – the image to be closed
easygraphics.load_image(filename: str) → easygraphics.image.Image

Load a image from the file.

Parameters:filename – the image file
Returns:the loaded image
easygraphics.put_image(x: int, y: int, src_image: easygraphics.image.Image, width: int = 0, height: int = 0, src_x: int = 0, src_y: int = 0, src_width: int = -1, src_height: int = -1, with_background=True, composition_mode=None, dst_image: easygraphics.image.Image = None)

Copy part of the source image (src_image) to the destination image (dst_image).

(x, y) specifies the top-left point in the destination image that is to be drawn onto.

(width, height) specifies the size of drawing part on the destination image.The default is (0, 0).

(src_x, src_y) specifies the top-left point of the part in the source image that is to be drawn. The default is (0, 0).

(src_width, src_height) specifies the size of the part of the source image that is to be drawn. The default, (0, 0) (and negative) means all the way to the bottom-right of the image.

if with_background is False, the source image’s background will not be copied.

The final result will depend on the composition mode and the source image’s background. In the default mode (CompositionMode.SOURCE_OVER), the transparent background in the source will not overwrite the destination.

param x:x coordinate value of the upper left point on the destination image
param y:y coordinate value of the upper left point on the destination image
param src_image:
 the source image to be copied
param width:width of the drawing part on the destination image
param height:height of the drawing part on the destination image
param src_x:x coordinate value of the top-left point of of the part to be drawn
param src_y:y coordinate value of the top-left point of of the part to be drawn
param src_width:
 witdh of the top-left point of of the part to be drawn
param src_height:
 height of the top-left point of of the part to be drawn
param with_background:
 if the background should be copied.
param composition_mode:
 if is None, use dst image’s composition mode to copy.
param dst_image:
 the target image which will be painted on. None means it is the target image (see set_target() and get_target()).
easygraphics.create_image_from_file(filename: str) → easygraphics.image.Image

Load a image from the file.

Parameters:filename – the image file
Returns:the loaded image
easygraphics.capture_screen(left: int, top: int, width: int, height: int, target_img: easygraphics.image.Image)

Capture specified region on the graphics windows to target image.

Parameters:
  • left – x coordinate of the capture region’s upper left corner
  • top – y coordinate of the capture region’s upper left corner
  • width – width of the capture region
  • height – height of the capture region
  • target_img – image to save the capture
easygraphics.get_image(left: int, top: int, width: int, height: int, target_img: easygraphics.image.Image)

Capture specified region on the graphics windows to target image.

Parameters:
  • left – x coordinate of the capture region’s upper left corner
  • top – y coordinate of the capture region’s upper left corner
  • width – width of the capture region
  • height – height of the capture region
  • target_img – image to save the capture
easygraphics.pause()

Pause the program and wait for mouse clicking or keyboard hitting.

>>> from easygraphics import *
>>> init_graph(800,600)
>>> pause()
>>> close_graph()
easygraphics.delay(milliseconds: int)

Delay the program for specified milliseconds.

Parameters:milliseconds – time to delay
easygraphics.delay_fps(fps: int)

Delay the program to control fps (Frame per seconds).

Valid fps value is 1-1000, this value is not checked for speed.

This function won’t skip frames.

Parameters:fps – the desire fps
Returns:False the graphics window is closed. True otherwise.
easygraphics.delay_jfps(fps, max_skip_count=0)

Delay to control fps with frame skipping.

If we don’t have enough time to delay, we’ll skip some frames.

Parameters:
  • fps – frames per second (max is 1000)
  • max_skip_count – max num of frames to skip (0 means no limit)
Returns:

True if this frame should not be skipped

easygraphics.is_run() → bool

Test if the graphics system is running.

Returns:True if the graphics system is running.
easygraphics.has_kb_msg() → bool

See if any key hit message in the message queue.

Use it with get_key().

Returns:True if hit, False otherwise
easygraphics.has_kb_hit() → bool

See if any ascii char key hit message in the message queue.

Use it with get_char().

Returns:True if hit, False otherwise
easygraphics.has_mouse_msg() → bool

See if there is any mouse message(event) in the message queue.

Use it with get_mouse_msg().

Returns:True if any mouse message, False otherwise
easygraphics.get_key() → easygraphics.graphwin.KeyMessage

Get the key inputted by keyboard.

If not any key is pressed in last 100 ms, the program will stop and wait for the next key hitting.

Returns:key message
easygraphics.get_char() → str

Get the ascii char inputted by keyboard.

If not any char key is pressed in last 100 ms, the program will stop and wait for the next key hitting.

Returns:the character inputted by keyboard
easygraphics.get_mouse_msg() → easygraphics.graphwin.MouseMessage

Get the mouse message.

If there is not any mouse message, the program will stop and wait for it.

Returns:mouse message
easygraphics.get_cursor_pos() -> (<class 'int'>, <class 'int'>)

Get position of the mouse cursor

Returns:position’s coordinate values (x,y)
easygraphics.get_click() → easygraphics.graphwin.MouseMessage

Get the mouse click message.

If there isn’t any clicked event, the program will stop and wait for it.

Returns:mouse message
easygraphics.contains_left_button(buttons) → bool

Test if the buttons contains the left mouse button.

The “buttons” should be values returned by get_click() or get_mouse()

Parameters:buttons – the buttons to be tested
Returns:if the buttons contains the left mouse button
easygraphics.contains_right_button(buttons) → bool

Test if the buttons contains the right mouse button.

The “buttons” should be values returned by get_click() or get_mouse()

Parameters:buttons – the buttons to be tested
Returns:if the buttons contains the right mouse button
easygraphics.contains_mid_button(buttons) → bool

Test if the buttons contains the middle mouse button.

The “buttons” should be values returned by get_click() or get_mouse()

Parameters:buttons – the buttons to be tested
Returns:if the buttons contains the middle mouse button
easygraphics.clear_key_msg()

Clear all keyboard hit messages.

easygraphics.clear_char_msg(self)

Clear all char key hit messages.

easygraphics.clear_mouse_msg(self)

Clear all mouse messages.

easygraphics.contains_alt(modifiers) → bool

Test if the modifiers contains the alt key

Parameters:modifiers – the modifiers to be tested
Returns:if the modifiers contains the alt key
easygraphics.contains_ctrl(modifiers) → bool

Test if the modifiers contains the control key

Parameters:modifiers – the modifiers to be tested
Returns:if the modifiers contains the control key
easygraphics.contains_meta(modifiers) → bool

Test if the modifiers contains the meta key

Parameters:modifiers – the modifiers to be tested
Returns:if the modifiers contains the meta key
easygraphics.contains_shift(modifiers) → bool

Test if the modifiers contains the shift key

Parameters:modifiers – the modifiers to be tested
Returns:if the modifiers contains the shift key
easygraphics.init_graph(width: int = 800, height: int = 600, headless: bool = False)

Init the easygraphics system and show the graphics window.

If “headless” is True, easygraphics will run in headless mode, which means there will be no graphics window. Use this mode if you want to draw and save image to files.

Parameters:
  • width – width of the graphics window (in pixels)
  • height – height of the graphics window (in pixels)
  • headless – True to run in headless mode.
>>> from easygraphics import *
>>> init_graph(800,600) #prepare and show a 800*600 window
easygraphics.close_graph()

Close the graphics windows.

The program will exit too.

>>> from easygraphics import *
>>> init_graph(800,600)
>>> pause()
>>> close_graph()
easygraphics.set_caption(title: str)

Set the graph window’s caption

Parameters:title – caption title
easygraphics.get_graphics_window() → easygraphics.graphwin.GraphWin

Get the graphics window.

Returns:the graphics window
easygraphics.show_image(image: easygraphics.image.Image = None)

Display the image in ipython console or notebook.

Parameters:image – the target image which will be displayed. None means it is the target image (see set_target() and get_target()).
easygraphics.begin_recording()

Start recording png animation

easygraphics.save_recording(filename: str)

Save the recording animation in PNG format.

Parameters:filename – the filename of the save file.
easygraphics.add_record(image: easygraphics.image.Image = None, **options)

Add one frame to the recording animation

Parameters:image – the target image whose content will be captured. None means it is the target image (see set_target() and get_target()).
easygraphics.end_recording()

End the recording of the animation.

easygraphics.color_gray(gray: int, alpha: int = 255) → <sphinx.ext.autodoc.importer._MockObject object at 0x7f50882d5150>

Create a gray color.

Parameters:
  • gray – gray value
  • alpha – alpha channel value of the color. 255 means fully opaque
Returns:

the color

easygraphics.color_rgb(red: int, green: int, blue: int, alpha: int = 255) → <sphinx.ext.autodoc.importer._MockObject object at 0x7f50882d5150>

Create a color with RGB color values r,g,b.

Parameters:
  • red – red value
  • green – green value
  • blue – blue value
  • alpha – alpha channel value of the color. 255 means fully opaque
Returns:

the color

easygraphics.color_cmyk(c: int, m: int, y: int, k: int, alpha: int = 255) → <sphinx.ext.autodoc.importer._MockObject object at 0x7f50882d5150>

Create a color with CMYK color values c,m,y,k.

Parameters:
  • c – cyan value
  • m – magenta value
  • y – yellow value
  • k – black value
  • alpha – alpha channel value of the color. 255 means fully opaque
Returns:

the color

easygraphics.color_hsv(h: int, s: int, v: int, alpha: int = 255) → <sphinx.ext.autodoc.importer._MockObject object at 0x7f50882d5150>

Create a color with HSV color values h,s,v.

Parameters:
  • h – hue value
  • s – saturation value
  • v – Value
  • alpha – alpha channel value of the color. 255 means fully opaque
Returns:

the color

easygraphics.color_hsl(h: int, s: int, l: int, alpha: int = 255) → <sphinx.ext.autodoc.importer._MockObject object at 0x7f50882d5150>

Create a color with HSL color values h,s,l.

Parameters:
  • h – hue value
  • s – saturation value
  • l – lightness value
  • alpha – alpha channel value of the color. 255 means fully opaque
Returns:

the color

easygraphics.rgb(red: int, green: int, blue: int, alpha: int = 255) → <sphinx.ext.autodoc.importer._MockObject object at 0x7f50882d5150>

Create a color with RGB color values r,g,b.

Parameters:
  • red – red value
  • green – green value
  • blue – blue value
  • alpha – alpha channel value of the color. 255 means fully opaque
Returns:

the color

easygraphics.to_alpha(new_color, alpha: int = None) → <sphinx.ext.autodoc.importer._MockObject object at 0x7f50882d5150>

Get new color based on the given color and alpha.

Parameters:
  • new_color – the base color
  • alpha – new color’s alpha
Returns:

new color with base color and the given alpha value

easygraphics.pol2cart(rho, theta)

Transform a point from polar coordinates to cartesian coordinates.

Parameters:
  • rho – rho coordinate value of the point
  • theta – theta coordinate value of the point (in radians)
Returns:

x,y coordinate value of the point

easygraphics.cart2pol(x, y)

Transform a point from cartesian coordinates to polar coordinates.

Parameters:
  • x – x coordinate value of the point
  • y – y coordinate value of the point
Returns:

rho (distance from the pole (origin) to the point), theta (the angle between the polar-axis and the line connecting the pole and the point, in radians)

easygraphics.ortho_look_at(eye_x: float, eye_y: float, eye_z: float, center_x: float, center_y: float, center_z: float, up_x: float, up_y: float, up_z: float) → <sphinx.ext.autodoc.importer._MockObject object at 0x7f5088335990>

Return the ortho projection matrix

Parameters:
  • eye_x
  • eye_y
  • eye_z
  • center_x
  • center_y
  • center_z
  • up_x
  • up_y
  • up_z
Returns:

the matrix

easygraphics.isometric_projection() → <sphinx.ext.autodoc.importer._MockObject object at 0x7f5088335990>

Return the isometric perspective projection matrix :return:

easygraphics.cart2sphere(x: float, y: float, z: float) -> (<class 'float'>, <class 'float'>, <class 'float'>)

Convert cartesian coordinate to spherical coordinate

Parameters:
  • x – x
  • y – y
  • z – z
Returns:

radius,θ,φ

easygraphics.sphere2cart(r: float, theta: float, phi: float) -> (<class 'float'>, <class 'float'>, <class 'float'>)

Convert spherical coordinate to cartesian coordinate

Parameters:
  • r – radius
  • theta – θ
  • phi – φ
Returns:

x,y,z

class easygraphics.Image(image: <sphinx.ext.autodoc.importer._MockObject object at 0x7f5087ba2410>)

The image class.

Use PyQt’s QImage to save the drawing, and QPainter as the underlying drawing device.

Note that the painter is keep and reused, if you want to draw on the image by yourself, please use get_painter() to get the painter and draw.And also note there is a mask image for background processing. You should get the mask right or you will get wrong result with set_background_color() and draw_image(with_background=False).

add_updated_listener(listener: Callable[[], None])

Add a listener for updated event.

Parameters:listener – the listener to add
arc(x1: float, y1: float, start_angle: float, end_angle: float, x2: float, y2: float)

Draw an elliptical arc from start_angle to end_angle. The base ellipse is centered at (x,y) which radius on x-axis is radius_x and radius on y-axis is radius_y.

Note: Positive values for the angles mean counter-clockwise while negative values mean the clockwise direction. Zero degrees is at the 3 o’clock position.
Parameters:
  • x1 – x coordinate value of the ellipse’s center
  • y1 – y coordinate value of the ellipse’s center
  • start_angle – start angle of the arc
  • end_angle – end angle of the arc
  • x2 – radius on x-axis of the ellipse
  • y2 – radius on y-axis of the ellipse
begin_shape(type=0)

Begin a shape definition

Parameters:type – the type of the shape. See VertexType const for more information
bezier(x0: float, y0: float, x1: float, y1: float, x2: float, y2: float, x3: float, y3: float)

Draw a cubic bezier curve.

points (x0,y0),(x1,y1),(x2,y2),(x3,y3) are the control points of the curve,

Parameters:
  • x0 – x coordinate of the first control point
  • y0 – y coordinate of the first control point
  • x1 – x coordinate of the second control point
  • y1 – y coordinate of the second control point
  • x2 – x coordinate of the third control point
  • y2 – y coordinate of the third control point
  • x3 – x coordinate of the fourth control point
  • y3 – y coordinate of the fourth control point
bezier_vertex(x1, y1, x2, y2, x3, y3)

Define a cubic Bezier curve. The first control point of the curve the vertex defined last time.

Parameters:
  • x1 – x pos of the second control point
  • y1 – y pos of the second control point
  • x2 – x pos of the third control point
  • y2 – y pos of the third control point
  • x3 – x pos of the fourth control point
  • y3 – y pos of the fourth control point
chord(x1: float, y1: float, start_angle: float, end_angle: float, x2: float, y2: float)

Draw an elliptical chord outline from start_angle to end_angle. The base ellipse is centered at (x,y) which radius on x-axis is radius_x and radius on y-axis is radius_y.

The chord is not filled.

Note: Positive values for the angles mean counter-clockwise while negative values mean the clockwise direction. Zero degrees is at the 3 o’clock position.
Parameters:
  • x1 – x coordinate value of the ellipse’s center
  • y1 – y coordinate value of the ellipse’s center
  • start_angle – start angle of the chord
  • end_angle – end angle of the chord
  • x2 – radius on x-axis of the ellipse
  • y2 – radius on y-axis of the ellipse
clear()

Clear the image to show the background.

clear_view_port()

Clear view port to show the background.

close()

Close and clean up the specified image.

Parameters:image – the image to be closed
copy(x: int, y: int, width: int, height: int) → easygraphics.image.Image

Create an copy of the image.

Parameters:
  • x – left-top of the copied area
  • y – left-top of the copied area
  • width – width of the copy area
  • height – height of the copy area
Returns:

new copy

static create(width: int, height: int) → easygraphics.image.Image

Create a new image.

Parameters:
  • width – width of the new image
  • height – height of the new image
Returns:

the created image

static create_from_file(filename: str) → easygraphics.image.Image

Load a image from the file.

Parameters:filename – the image file
Returns:the loaded image
curve(*points)

Draw a Catmull-Rom spline.

Parameters:points – control points
curve_vertex(x: float, y: float)

Define a Catmull-Rom curve vertex.

Parameters:
  • x – x pos of the vertex
  • y – y pos of the vertex
draw_arc(x1: float, y1: float, start_angle: float, end_angle: float, x2: float, y2: float)

Draw an elliptical arc from start_angle to end_angle. The base ellipse is centered at (x,y) which radius on x-axis is radius_x and radius on y-axis is radius_y.

Note: Positive values for the angles mean counter-clockwise while negative values mean the clockwise direction. Zero degrees is at the 3 o’clock position.
Parameters:
  • x1 – x coordinate value of the ellipse’s center
  • y1 – y coordinate value of the ellipse’s center
  • start_angle – start angle of the arc
  • end_angle – end angle of the arc
  • x2 – radius on x-axis of the ellipse
  • y2 – radius on y-axis of the ellipse
draw_bezier(x0: float, y0: float, x1: float, y1: float, x2: float, y2: float, x3: float, y3: float)

Draw a cubic bezier curve.

points (x0,y0),(x1,y1),(x2,y2),(x3,y3) are the control points of the curve,

Parameters:
  • x0 – x coordinate of the first control point
  • y0 – y coordinate of the first control point
  • x1 – x coordinate of the second control point
  • y1 – y coordinate of the second control point
  • x2 – x coordinate of the third control point
  • y2 – y coordinate of the third control point
  • x3 – x coordinate of the fourth control point
  • y3 – y coordinate of the fourth control point
draw_chord(x1: float, y1: float, start_angle: float, end_angle: float, x2: float, y2: float)

Draw an elliptical chord outline from start_angle to end_angle. The base ellipse is centered at (x,y) which radius on x-axis is radius_x and radius on y-axis is radius_y.

The chord is filled and has outline

Note: Positive values for the angles mean counter-clockwise while negative values mean the clockwise direction. Zero degrees is at the 3 o’clock position.
Parameters:
  • x1 – x coordinate value of the ellipse’s center
  • y1 – y coordinate value of the ellipse’s center
  • start_angle – start angle of the chord
  • end_angle – end angle of the chord
  • x2 – radius on x-axis of the ellipse
  • y2 – radius on y-axis of the ellipse
draw_curve(*points)

Draw a Catmull-Rom spline.

Parameters:points – control points
draw_ellipse(x1: float, y1: float, x2: float, y2: float)

Draw an ellipse centered at (x,y) , radius on x-axis is radius_x, radius on y-axis is radius_y.

The ellipse is filled and has outline.

Parameters:
  • x1 – x coordinate value of the ellipse’s center
  • y1 – y coordinate value of the ellipse’s center
  • x2 – radius on x-axis of the ellipse
  • y2 – radius on y-axis of the ellipse
draw_image(x: int, y: int, image: easygraphics.image.Image, width: int = 0, height: int = 0, src_x: int = 0, src_y: int = 0, src_width: int = 0, src_height: int = 0, with_background=True, composition_mode=None)

Copy part of the source image (src_image) to the destination image (dst_image).

(x, y) specifies the top-left point in the destination image that is to be drawn onto.

(width, height) specifies the size of drawing part on the destination image.The default is (0, 0).

(src_x, src_y) specifies the top-left point of the part in the source image that is to be drawn. The default is (0, 0).

(src_width, src_height) specifies the size of the part of the source image that is to be drawn. The default, (0, 0) (and negative) means all the way to the bottom-right of the image.

if with_background is False, the source image’s background will not be copied.

The final result will depend on the composition mode and the source image’s background. In the default mode (CompositionMode.SOURCE_OVER), the transparent background in the source will not overwrite the destination.

Parameters:
  • x – x coordinate value of the upper left point on the destination image
  • y – y coordinate value of the upper left point on the destination image
  • image – the source image to be copied
  • width – width of the drawing part on the destination image
  • height – height of the drawing part on the destination image
  • src_x – x coordinate value of the top-left point of of the part to be drawn
  • src_y – y coordinate value of the top-left point of of the part to be drawn
  • src_width – witdh of the top-left point of of the part to be drawn
  • src_height – height of the top-left point of of the part to be drawn
  • with_background – if the background should be copied.
  • composition_mode – if is None, use dst image’s composition mode to copy.
draw_line(x1: float, y1: float, x2: float, y2: float)

Draw a line from (x1,y1) to (x2,y2) on the specified image.

Parameters:
  • x1 – x coordinate value of the start point
  • y1 – y coordinate value of the start point
  • x2 – x coordinate value of the end point
  • y2 – y coordinate value of the start point
draw_lines(*points)

Draw lines.

“points” is a 2D point pair list. It should contain even number of points, and each 2 points make a point pair. And each point have 2 coordinate values(x,y). So if you have n point pairs, the points list should have 4*n values.

For examples , if points is [50,50,550,350, 50,150,550,450, 50,250,550,550], draw_lines() will draw 3 lines: (50,50) to (550,350), (50,150) to (550,450), (50,250) to (550,550)

Parameters:points – point value list
draw_path(path: <sphinx.ext.autodoc.importer._MockObject object at 0x7f5087ba2410>)

Draw and fill a path.

Parameters:path – path to drawn and fill
draw_pie(x1: float, y1: float, start_angle: float, end_angle: float, x2: float, y2: float)

Draw an elliptical pie from start_angle to end_angle. The base ellipse is centered at (x,y) which radius on x-axis is radius_x and radius on y-axis is radius_y.

The pie is filled and has outline.

Note: Positive values for the angles mean counter-clockwise while negative values mean the clockwise direction. Zero degrees is at the 3 o’clock position.
Parameters:
  • x1 – x coordinate value of the ellipse’s center
  • y1 – y coordinate value of the ellipse’s center
  • start_angle – start angle of the pie
  • end_angle – end angle of the pie
  • x2 – radius on x-axis of the ellipse
  • y2 – radius on y-axis of the ellipse
draw_point(x: float, y: float)

Draw a point at (x,y) on the specified image.

Parameters:
  • x – x coordinate value of the drawing point
  • y – y coordinate value of the drawing point
draw_poly_line(*end_points)

Draw a poly line.

“end_points” is a 2D points list. Each 2 values in the list make a point. A poly line will be drawn to connect adjacent end_points defined by the the list.

For examples , if “end_points” is [50,50,550,350, 50,150,550,450, 50,250,550,550], draw_poly_line() will draw 5 lines: (50,50) to (550,350), (550,350) to (50,150), (50,150) to (550,450), (550,540) to (50,250) and(50,250) to (550,550).

Parameters:end_points – point value list
draw_polygon(*vertices)

Draw a polygon.

“vertices” is a 2D point list. Each 2 values in the list make a point. A polygon will be drawn to connect adjacent points defined by the the list.

For examples , if “vertices” is [50,50,550,350, 50,150], draw_polygon() will draw a triangle with vertices at (50,50) , (550,350) and (50,150)

The polygon is filled and has outline.

Parameters:vertices – point value list
draw_quadratic(x0, y0, x1, y1, x2, y2)

Draw a quadratic bezier curve.

points (x0,y0),(x1,y1),(x2,y2) are the control points of the curve,

Parameters:
  • x0 – x coordinate of the first control point
  • y0 – y coordinate of the first control point
  • x1 – x coordinate of the second control point
  • y1 – y coordinate of the second control point
  • x2 – x coordinate of the third control point
  • y2 – y coordinate of the third control point
draw_rect(x1: float, y1: float, x2: float, y2: float)

Draws a rectangle with upper left corner at (left, top) and lower right corner at (right,bottom).

The rectangle is filled and has outline.

Parameters:
  • x1 – x coordinate value of the upper left corner
  • y1 – y coordinate value of the upper left corner
  • x2 – x coordinate value of the lower right corner
  • y2 – y coordinate value of the lower right corner
draw_rect_text(x: int, y: int, width: int, height: int, flags=<sphinx.ext.autodoc.importer._MockObject object>, *args, sep=' ')

Print the given texts in the specified rectangle area.

Flags are defined as TextFlag const.

Parameters:
  • x – x coordinate of the output rectangle’s upper left corner
  • y – y coordinate of the output rectangle’s upper left corner
  • width – width of the output rectangle
  • height – height of the output rectangle
  • args – things to be printed (like print())
  • flags – align flags
  • sep – seperator used to join strings
draw_rounded_rect(x1: float, y1: float, x2: float, y2: float, round_x: float, round_y: float)

Draws a rounded rectangle with upper left corner at (left, top) , lower right corner at (right,bottom). raidus on x-axis of the corner ellipse arc is round_x, radius on y-axis of the corner ellipse arc is round_y.

The rectangle is filled and has outline.

Parameters:
  • x1 – x coordinate value of the upper left corner
  • y1 – y coordinate value of the upper left corner
  • x2 – x coordinate value of the lower right corner
  • y2 – y coordinate value of the lower right corner
  • round_x – raidus on x-axis of the corner ellipse arc
  • round_y – radius on y-axis of the corner ellipse arc
draw_text(x: int, y: int, *args, sep=' ')

Prints the given texts beginning at the given position (x,y).

Parameters:
  • x – x coordinate value of the start point
  • y – y coordinate value of the start point
  • args – things to be printed
  • sep – seperator used to join strings
draw_to_device(device: <sphinx.ext.autodoc.importer._MockObject object at 0x7f5087ba2410>)

Draw the whole image to the specified device.

Parameters:device – the device to be drawn on
ellipse(x1: float, y1: float, x2: float, y2: float)

Draw an ellipse outline centered at (x,y) , radius on x-axis is radius_x, radius on y-axis is radius_y.

The ellipse is not filled.

Parameters:
  • x1 – x coordinate value of the ellipse’s center
  • y1 – y coordinate value of the ellipse’s center
  • x2 – radius on x-axis of the ellipse
  • y2 – radius on y-axis of the ellipse
end_shape(close=False)

End a shape definition

Parameters:close – if the shape should be closed. Only polylines can be closed.
fill_chord(x1: float, y1: float, start_angle: float, end_angle: float, x2: float, y2: float)

Draw an elliptical chord outline from start_angle to end_angle. The base ellipse is centered at (x,y) which radius on x-axis is radius_x and radius on y-axis is radius_y.

The chord doesn’t have outline.

Note: Positive values for the angles mean counter-clockwise while negative values mean the clockwise direction. Zero degrees is at the 3 o’clock position.
Parameters:
  • x1 – x coordinate value of the ellipse’s center
  • y1 – y coordinate value of the ellipse’s center
  • start_angle – start angle of the chord
  • end_angle – end angle of the chord
  • x2 – radius on x-axis of the ellipse
  • y2 – radius on y-axis of the ellipse
fill_ellipse(x1: float, y1: float, x2: float, y2: float)

Fill an ellipse centered at (x,y) , radius on x-axis is radius_x, radius on y-axis is radius_y.

The ellipse dosen’t has outline.

Parameters:
  • x1 – x coordinate value of the ellipse’s center
  • y1 – y coordinate value of the ellipse’s center
  • x2 – radius on x-axis of the ellipse
  • y2 – radius on y-axis of the ellipse
fill_image(color)

Fill the whole image with the specified color.

Parameters:color – the fill color
fill_path(path: <sphinx.ext.autodoc.importer._MockObject object at 0x7f5087ba2410>)

Fill the region enclosed by the path

Parameters:path – the path enclosing the region
fill_pie(x1: float, y1: float, start_angle: float, end_angle: float, x2: float, y2: float)

Fill an elliptical pie from start_angle to end_angle. The base ellipse is centered at (x,y) which radius on x-axis is radius_x and radius on y-axis is radius_y.

The pie doesn’t have outline.

Note: Positive values for the angles mean counter-clockwise while negative values mean the clockwise direction. Zero degrees is at the 3 o’clock position.
Parameters:
  • x1 – x coordinate value of the ellipse’s center
  • y1 – y coordinate value of the ellipse’s center
  • start_angle – start angle of the pie
  • end_angle – end angle of the pie
  • x2 – radius on x-axis of the ellipse
  • y2 – radius on y-axis of the ellipse
fill_polygon(*vertices)

Fill a polygon.

“vertices” is a 2D point list. Each 2 values in the list make a point. A polygon will be drawn to connect adjacent points defined by the the list.

For examples , if “vertices” is [50,50,550,350, 50,150], fill_polygon() will fill a triangle with vertices at (50,50) , (550,350) and (50,150).

The polygon doesn’t have outline.

Parameters:vertices – point value list
fill_rect(x1: float, y1: float, x2: float, y2: float)

Draws a rectangle with upper left corner at (left, top) and lower right corner at (right,bottom).

The rectangle doesn’t have outline.

Parameters:
  • x1 – x coordinate value of the upper left corner
  • y1 – y coordinate value of the upper left corner
  • x2 – x coordinate value of the lower right corner
  • y2 – y coordinate value of the lower right corner
fill_rounded_rect(x1: float, y1: float, x2: float, y2: float, round_x: float, round_y: float)

Fill a rounded rectangle with upper left corner at (left, top) , lower right corner at (right,bottom). raidus on x-axis of the corner ellipse arc is round_x, radius on y-axis of the corner ellipse arc is round_y.

The rectangle doesn’t have outline.

Parameters:
  • x1 – x coordinate value of the upper left corner
  • y1 – y coordinate value of the upper left corner
  • x2 – x coordinate value of the lower right corner
  • y2 – y coordinate value of the lower right corner
  • round_x – radius on x-axis of the corner ellipse arc
  • round_y – radius on y-axis of the corner ellipse arc
flip(x: float, y: float, x1: float = 0, y1: float = 0)

Reflect the coordinates against the line passing (x1,y1) and (x,y).

Note that all things will get reflected, including text! If you just want to draw on a normal coordinate system with the y-axis grows bottom up, use set_flip_y()..

Parameters:
  • x – x coordinate value of the first point
  • y – y coordinate value of the first point
  • x1 – the x coordinate of the second point
  • y1 – the y coordinate of the second point
flood_fill(x: int, y: int, border_color)

Flood fill the image starting from(x,y) and ending at borders with border_color.

The fill region border must be closed,or the whole image will be filled!

Parameters:
  • x – x coordinate value of the start point
  • y – y coordinate value of the start point
  • border_color – color of the fill region border
get_background_color()

Get the background color of the image.

Returns:background color
get_brush() → <sphinx.ext.autodoc.importer._MockObject object at 0x7f5087ba2410>

Get brush of the image

Returns:the brush
get_color()

Get the foreground (drawing) color of the specified image.

It will be used when drawing lines or shape outlines.

Returns:foreground color
get_composition_mode()

Get composition mode of the specified image.

When drawing ,the composition mode will decide how the result pixel color will be computed
(using source color and color of the destination).
Returns:composition mode
get_ellipse_mode()
get_fill_color()

Get the fill color of the specified image.

It will be used when drawing and fill shapes.

Returns:fill color
get_fill_rule()

Get the fill rule (algorithm) for filling polygons.

Returns:the rule used for filling polygons
get_fill_style()

Get fill style of the specified image.

It will be used when drawing and fill shapes.

Returns:fill style
get_font() → <sphinx.ext.autodoc.importer._MockObject object at 0x7f5087ba2410>

Get font of the specified image.

Returns:the font used by the specified image
get_font_size() → int

Get font size of the specified image.

Returns:font size of the specified image
get_height()

Get the height of the image.

Returns:image height
get_image() → <sphinx.ext.autodoc.importer._MockObject object at 0x7f5087ba2410>

Get the internal QImage.

note EasyGraphics don’t require and release qpainter each time. Because there can only be one QPainter for each QImage at time, so if you want to draw on this image customly, use get_painter() to get the internal QPainter instance.

Returns:the QImage instance used internally
get_line_style()

Get line style.

The line style will be used when drawing lines and shape outlines.

Returns:line style
get_line_width() → float

Get line width (thickness).

It will be used when drawing lines or shape outlines.

Returns:line width
get_mask() → <sphinx.ext.autodoc.importer._MockObject object at 0x7f5087ba2410>

Get background mask image.

Returns:background mask
get_mask_painter() → <sphinx.ext.autodoc.importer._MockObject object at 0x7f5087ba2410>

Get the QPainter instance for drawing the mask.

Returns:the mask painter used internally
get_painter() → <sphinx.ext.autodoc.importer._MockObject object at 0x7f5087ba2410>

Get the QPainter instance for drawing the image.

Returns:the painter used internally
get_pen() → <sphinx.ext.autodoc.importer._MockObject object at 0x7f5087ba2410>

Get the pen of the image

Returns:pen
get_pixel(x: int, y: int) → <sphinx.ext.autodoc.importer._MockObject object at 0x7f5087ba2410>

Get a pixel’s color on the specified image.

Parameters:
  • x – x coordinate value of the pixel
  • y – y coordinate value of the pixel
Returns:

color of the pixel

get_rect_mode()
get_transform() → <sphinx.ext.autodoc.importer._MockObject object at 0x7f5087ba2410>

Get transform matrix of the image.

Returns:the transform matrix
get_width() → int

Get the width of the image.

Returns:image width
get_x() → float

Get the x coordinate value of the current drawing position (x,y).

Some drawing functions will use the current pos to draw.(see line_to(),line_rel(),move_to(),move_rel()).

Returns:the x coordinate value of the current drawing position
get_y() → float

Get the y coordinate value of the current drawing position (x,y).

Some drawing functions will use the current pos to draw.(see line_to(),line_rel(),move_to(),move_rel())

Returns:the y coordinate value of the current drawing position
line(x1: float, y1: float, x2: float, y2: float)

Draw a line from (x1,y1) to (x2,y2) on the specified image.

Parameters:
  • x1 – x coordinate value of the start point
  • y1 – y coordinate value of the start point
  • x2 – x coordinate value of the end point
  • y2 – y coordinate value of the start point
line_rel(dx: float, dy: float)

Draw a line from the current drawing position (x,y) to (x+dx,y+dy), then set the drawing position is set to (x+dx,y+dy).

Parameters:
  • dx – x coordinate offset of the new drawing position
  • dy – y coordinate offset of the new drawing position
line_to(x: float, y: float)

Draw a line from the current drawing position to (x,y), then set the drawing position is set to (x,y).

Parameters:
  • x – x coordinate value of the new drawing position
  • y – y coordinate value of the new drawing position
lines(*points)

Draw lines.

“points” is a 2D point pair list. It should contain even number of points, and each 2 points make a point pair. And each point have 2 coordinate values(x,y). So if you have n point pairs, the points list should have 4*n values.

For examples , if points is [50,50,550,350, 50,150,550,450, 50,250,550,550], draw_lines() will draw 3 lines: (50,50) to (550,350), (50,150) to (550,450), (50,250) to (550,550)

Parameters:points – point value list
mirror(x: float, y: float, x1: float = 0, y1: float = 0)

Reflect the coordinates against the line passing (x1,y1) and (x,y).

Note that all things will get reflected, including text! If you just want to draw on a normal coordinate system with the y-axis grows bottom up, use set_flip_y()..

Parameters:
  • x – x coordinate value of the first point
  • y – y coordinate value of the first point
  • x1 – the x coordinate of the second point
  • y1 – the y coordinate of the second point
move_rel(dx: float, dy: float)

Move the drawing position by (dx,dy).

If the old position is (x,y), then the new position will be (x+dx,y+dy).

The drawing position is used by line_to(), line_rel().

Parameters:
  • dx – x coordinate offset of the new drawing position
  • dy – y coordinate offset of the new drawing position
move_to(x, y)

Set the drawing position to (x,y).

The drawing position is used by line_to(), line_rel() and move_rel().

Parameters:
  • x – x coordinate value of the new drawing position
  • y – y coordinate value of the new drawing position
path(path: <sphinx.ext.autodoc.importer._MockObject object at 0x7f5087ba2410>)

Draw a path.

Parameters:path – path to be drawn
pie(x1: float, y1: float, start_angle: float, end_angle: float, x2: float, y2: float)

Draw an elliptical pie outline from start_angle to end_angle. The base ellipse is centered at (x,y) which radius on x-axis is radius_x and radius on y-axis is radius_y.

The pie is not filled.

Note: Positive values for the angles mean counter-clockwise while negative values mean the clockwise direction. Zero degrees is at the 3 o’clock position.
Parameters:
  • x1 – x coordinate value of the ellipse’s center
  • y1 – y coordinate value of the ellipse’s center
  • start_angle – start angle of the pie
  • end_angle – end angle of the pie
  • x2 – radius on x-axis of the ellipse
  • y2 – radius on y-axis of the ellipse
poly_line(*end_points)

Draw a poly line.

“end_points” is a 2D points list. Each 2 values in the list make a point. A poly line will be drawn to connect adjacent end_points defined by the the list.

For examples , if “end_points” is [50,50,550,350, 50,150,550,450, 50,250,550,550], draw_poly_line() will draw 5 lines: (50,50) to (550,350), (550,350) to (50,150), (50,150) to (550,450), (550,540) to (50,250) and(50,250) to (550,550).

Parameters:end_points – point value list
polygon(*vertices)

Draw polygon outline.

“vertices” is a 2D point list. Each 2 values in the list make a point. A polygon will be drawn to connect adjacent points defined by the the list.

For examples , if “vertices” is [50,50,550,350, 50,150], polygon() will draw a triangle with vertices at (50,50) , (550,350) and (50,150).

The polygon is not filled.

Parameters:vertices – point value list
pop_transform()

Pop the last saved transform from the transform stack, and use it as the current transform.

push_transform()

Push (save) the current transform to the transform stack.

put_pixel(x: int, y: int, color)

Set a pixel’s color on the specified image.

Parameters:
  • x – x coordinate value of the pixel
  • y – y coordinate value of the pixel
  • color – the color
quadratic(x0, y0, x1, y1, x2, y2)

Draw a quadratic bezier curve.

points (x0,y0),(x1,y1),(x2,y2) are the control points of the curve,

Parameters:
  • x0 – x coordinate of the first control point
  • y0 – y coordinate of the first control point
  • x1 – x coordinate of the second control point
  • y1 – y coordinate of the second control point
  • x2 – x coordinate of the third control point
  • y2 – y coordinate of the third control point
quadratic_vertex(x1, y1, x2, y2)

Define a quadratic Bezier curve vertex. The first control point of the curve the vertex defined last time.

Parameters:
  • x1 – x pos of the second control point
  • y1 – y pos of the second control point
  • x2 – x pos of the third control point
  • y2 – y pos of the third control point
rect(x1: float, y1: float, x2: float, y2: float)

Draws a rectangle outline with upper left corner at (left, top) and lower right corner at (right,bottom).

The rectangle is not filled.

Parameters:
  • x1 – x coordinate value of the upper left corner
  • y1 – y coordinate value of the upper left corner
  • x2 – x coordinate value of the lower right corner
  • y2 – y coordinate value of the lower right corner
reflect(x: float, y: float, x1: float = 0, y1: float = 0)

Reflect the coordinates against the line passing (x1,y1) and (x,y).

Note that all things will get reflected, including text! If you just want to draw on a normal coordinate system with the y-axis grows bottom up, use set_flip_y()..

Parameters:
  • x – x coordinate value of the first point
  • y – y coordinate value of the first point
  • x1 – the x coordinate of the second point
  • y1 – the y coordinate of the second point
remove_updated_listener(listener: Callable[[], None])

Remove a updated event listener.

Parameters:listener – the listener to remove
reset_transform()

Reset all transforms (translate/rotate/scale).

reset_view_port()

Reset the view port setting.

reset_window()

Reset/remove the logical window.(see set_window())

restore_settings()

Restore previously saved drawing settings.

See save_settings().

Note: current position won’t be saved and restored.

rotate(degree: float, x: float = 0, y: float = 0)

Rotates the coordinate system around the point (x,y) with the given angle (in degree) clockwise.

Parameters:
  • degree – the rotate angle (in degree)
  • x – the x coordinate of the rotation center
  • y – the y coordinate of the rotation center
rounded_rect(x1: float, y1: float, x2: float, y2: float, round_x: float, round_y: float)

Draws a rounded rectangle outline with upper left corner at (left, top) , lower right corner at (right,bottom). Raidus on x-axis of the corner ellipse arc is round_x, radius on y-axis of the corner ellipse arc is round_y.

The rectangle is not filled.

Parameters:
  • x1 – x coordinate value of the upper left corner
  • y1 – y coordinate value of the upper left corner
  • x2 – x coordinate value of the lower right corner
  • y2 – y coordinate value of the lower right corner
  • round_x – raidus on x-axis of the corner ellipse arc
  • round_y – radius on y-axis of the corner ellipse arc
save(filename: str, with_background=True)

Save image to file.

Set with_background to False to get a transparent background image.

Note that JPEG format doesn’t support transparent. Use PNG format if you want a transparent background.

Parameters:
  • filename – path of the file
  • with_background – True to save the background together. False not
save_settings()

Save current drawing settings.

See restore_settings().

Note: current position won’t be saved and restored.

scale(sx: float, sy: float)

Scales the coordinate system by (sx, sy).

Parameters:
  • sx – scale factor on x axis.
  • sy – scale factor on y axis.
scaled(width: int, height: int) → easygraphics.image.Image

Create a scaled copy with the specified width and height. :param width: width of the copy :param height: height of the copy :return: new copy

set_antialiasing(anti: bool = True)

Set Anti Aliasing

Parameters:anti – if antialiasing should be set
set_background_color(background_color)

Set and change the background color.

The possible color could be consts defined in Color class, or the color created by rgb() function, or PyQt5’s QColor , QGradient object or QtCore.Qt.GlobalColor consts (see the pyqt reference).

Parameters:background_color – background color
set_brush(brush: <sphinx.ext.autodoc.importer._MockObject object at 0x7f5087ba2410>)

Set the brush.

Parameters:brush – the brush
set_clip_rect(left: int, top: int, right: int, bottom: int)

Set the clip rect.

Drawings outside the clip rect will be clipped.

Parameters:
  • left – left of the clip rectangle
  • top – top of the clip rectangle
  • right – right of the clip rectangle
  • bottom – bottom of the clip rectangle
set_clipping(clipping: bool)

Set clipping.

Use set_clip_rect() to set the clip rectangle.

Parameters:clipping – True will turn on clipping, False will turn off clipping
set_color(color)

Set the foreground (drawing) color of the specified image.

It will be used when drawing lines or shape outlines.

The possible color could be consts defined in Color class, or the color created by rgb() function, or PyQt5’s QColor , QGradient object or QtCore.Qt.GlobalColor consts (see the pyqt reference).

Parameters:color – foreground color
set_composition_mode(mode)

Get composition mode of the specified image.

Composition modes are used to specify how the pixels in the source (image/pen/brush), are merged with the pixel in the destination image.

Parameters:mode – composition mode
set_ellipse_mode(mode)
set_fill_color(fill_color)

Set the fill (drawing) color of the specified image.

It will be used when drawing and fill shapes.

The possible color could be consts defined in Color class, or the color created by rgb() function, or PyQt5’s QColor , QGradient object or QtCore.Qt.GlobalColor consts (see the pyqt reference).

Parameters:fill_color – fill color
set_fill_rule(rule)

Set the fill rule (algorithm) for filling polygons.

Parameters:rule – the rule to be used for filling polygons
set_fill_style(fill_style)

Set fill style of the specified image.

It will be used when drawing and fill shapes. Valid values are the consts defined in FillStyle

Parameters:fill_style – fill style
set_flip_y(flip_y: bool) → None

Reflect with x-aixs as the axis (upside down). Texts will not flip.

Don’t translate the origin to other points (but you can translate and then translate back) before drawing any text. Or the text position’s calculation will get wrong! So if you want to set the origin to the image/image’s center, call set_flip_y() after the set_origin() or translate()!

Note: Use this functions instead of the reflect()/flip()/mirror(),if you only want to draw on an ordinary coordinate system with y-axis grows bottom-up.

Parameters:flip_y – True to turn on the flip, False to turn off.
set_font(font: <sphinx.ext.autodoc.importer._MockObject object at 0x7f5087ba2410>)

Set font of the specified image.

Parameters:font – the font will be used
set_font_size(size: int)

Set font size of the specified image.

Parameters:size – font size of the specified image
set_line_style(line_style)

Set line style.

The line style will be used when drawing lines and shape outlines. Possible value is one of the consts defined in LineStyle.

Parameters:line_style – line style
set_line_width(width: float)

Set line width (thinkness).

It will be used when drawing lines or shape outlines.

Parameters:width – line width
set_pen(pen: <sphinx.ext.autodoc.importer._MockObject object at 0x7f5087ba2410>)

Set pen.

Parameters:pen – the pen to use.
Returns:
set_rect_mode(mode)
set_transform(transform: <sphinx.ext.autodoc.importer._MockObject object at 0x7f5087ba2410>)

Set image’s transform matrix.

Parameters:transform – the transform matrix to set
set_view_port(left: int, top: int, right: int, bottom: int)

Set the view port of the the specified image.

View port is the drawing zone on the image.

The drawing outside the view port is not clipped. If you want to clip the drawing ,use set_clip_rect()

if view port and “logical window” don’t have the same width and height, drawing will get zoomed. So set_window() is often used with the set_view_port

Parameters:
  • left – left of the view port rectangle
  • top – top of the view port rectangle
  • right – right of the view port rectangle
  • bottom – bottom of the view port rectangle
set_window(left: int, top: int, width: int, height: int)

Set the logical drawing window.

All your drawing is first drawing on the logical window, then mapping to view port (see set_view_port()). The logical window’s 4 corner points to streched to match the view port.

If your view port is 200x200,and you use set_window(-50,-50,100,100) to get a 100x100 logical window with the left-top corner at (-50,-50) , then the logical window’s left corner (-50,-50) is set to view port’s (0,0), and right-bottom corner (50,50) is set to view port’s right bottom corner (200,200). All logical points is mapping accordingly.

If you just want to transform the drawing, use set_origin()/translate()/rotate()/scale().

The drawing outside the logical window is not clipped. If you want to clip it, use set_clip_rect().

Parameters:
  • left – x pos of the logical window’s left-top corner
  • top – y pos of the logical window’s left-top corner
  • width – width of the logical window
  • height – height of the logical window
shear(sh: float, sv: float, x: float = 0, y: float = 0)

Shear (skew) the coordinates around the point (x,y) by sh,sv.

Parameters:
  • sh – shear ratio on the x-axis
  • sv – shear ratio on the y-axis
  • x – the x coordinate of the skew center
  • y – the y coordinate of the skew center
skew(sh: float, sv: float, x: float = 0, y: float = 0)

Shear (skew) the coordinates around the point (x,y) by sh,sv.

Parameters:
  • sh – shear ratio on the x-axis
  • sv – shear ratio on the y-axis
  • x – the x coordinate of the skew center
  • y – the y coordinate of the skew center
text_height() → int

Return height of the text (font height).

Returns:height of the text (font height)
text_width(text: str) → int

Return width of the text.

Parameters:text – the text
Returns:width of the text
to_bytes(with_background=True, format: str = 'PNG') → bytes

Convert the image to the specified format (i.e. PNG format) bytes.

Parameters:
  • with_background – True to save the background together. False not
  • format – format of the bytes content
Returns:

bytes in the specified format

translate(offset_x: float, offset_y: float)

Translates the coordinate system by the given offset; i.e. the given offset is added to points.

Parameters:
  • offset_x – offset on the x coordinate
  • offset_y – offset on the y coordinate
vertex(x: float, y: float)

Define a vertex.

Parameters:
  • x – x pos of the vertex
  • y – y pos of the vertex
easygraphics.easy_run(main_func: Callable, width=640, height=480)
easygraphics.in_easy_run_mode() → bool
easygraphics.register_for_clean_up(obj)

Register an object for clean up when the app quits.

Tutorials

Graphics

The First window

In this program, we will create and show a graphics window:

  1. Define the easygraphics main function

    In the main function, we:

    1. Init the graphics window
    2. wait for mouse click or keyboard hitting
    3. close the graphics system (and graphics window)
  2. Run the main function

note 1 : You must use easy_run() to run the main function.

note 2 : init_graph() must be called before any easygraphics drawing functions.

note 3 : Don’t forget to close_graph() to clean up the system after all drawing work is done.

note 4 : You can use the graphics window’s close button to close the graphics system. But this may cause exception. (When there are unfinished drawing operations.)

from easygraphics import *

def main():
    init_graph(800, 600)
    pause()
    close_graph()

easy_run(main)

The First Drawing

Let’s draw a line from (0,0) to (640,480)

In computer graphics, we normally use a screen coordinate system as below:

_images/coordinates.png

In this system, the origin (0,0) is at screen’s upper left corner, and y-axis is growing top-down.

So the result is a line from upper left corner to lower right corner.

_images/02_first_drawing.png
from easygraphics import *

def main():
    init_graph(640, 480)
    line(0, 0, 640, 480)
    pause()
    close_graph()

easy_run(main)

Color System

Color System Summary

Easy Graphics uses Qt’s Color System

A color is normally specified in terms of RGB (red, green, and blue) components ( using color_rgb()), but it is also possible to specify it in terms of HSV (hue, saturation, and value) (using color_hsv())and CMYK (cyan, magenta, yellow and black) components (user color_cymk()).

qcolor-rgb qcolor-hsv qcolor-cmyk
RGB HSV CMYK

Instead of RGB, HSV or CMYK values, A color can be set by passing an RGB string (such as “#112233”), or an ARGB string (such as “#ff112233”) or a color name (such as “blue”). The color names are taken from the SVG 1.0 color names.

The color components can be retrieved individually, e.g with red(), hue() and cyan() member functions. The values of the color components can also be retrieved in one go using the getRgb(), getHsv() and getCmyk() member functions.

Predefined Colors

There are 24 predefined colors described by the Color constants.

_images/consts-color.jpg
Summary

So to set the pen’s color to red , we can:

  1. Use predefined Color const

    set_color(Color.RED)
    
  2. Use RGB values and color_rgb() function

    set_color(color_rgb(255,0,0))
    
  3. Use a color name

    set_color("red")
    
  4. Use a css web color string

    set_color("#ff0000")
    
  5. Use a rgb integer

    set_color(0xff0000)
    
Transparency (Alpha Value)

Like most modern graphic systems, Easygraphics ( and its underlying Qt System) use a alpha component to represent the transparency of a pixel on the image. When the alpha value is 255, the pixel is fully opaque; when the alpha value is 0, the pixel is fully tranparent.

All the color functions (color_rgb()/color_hsv()/color_cmyk()) has an optional parameter “alpha” to make a color with transparency. The default value of this parameter is 255, which means the color is fully opaque.

You can use to_alpha() function to make a tranparency color by string or rgb integers.

The following code set the foreground color to a red with 150 as alpha value ( about half transparent)

set_color(to_alpha("red",150))

Lines and Points

Drawing Points

You can use draw_point() to draw a point. The size of point is determined by line width (pen size); If you want to draw a pixel, use put_pixel() instead.

Drawing Lines

You can use line() to draw a line.

Draw with the Current Position

In easygraphics, each image (including the graphics window) stores “a current position”. Use this position, we can draw lines relatively.

The related functions are:

get_drawing_x(image) Get the x coordinate value of the current drawing position (x,y).
get_drawing_y(image) Get the y coordinate value of the current drawing position (x,y).
get_drawing_pos(image) Get the current drawing position (x,y).
move_to(x, y, image) Set the drawing position to (x,y).
move_rel(dx, dy, image) Move the drawing position by (dx,dy).
line_to(x, y, image) Draw a line from the current drawing position to (x,y), then set the drawing position is set to (x,y).
line_rel(dx, dy, image) Draw a line from the current drawing position (x,y) to (x+dx,y+dy), then set the drawing position is set to (x+dx,y+dy).

The following program draws a dash line by using the current position.

from easygraphics import *

def main():
    init_graph(400, 100)

    move_to(50, 50)
    for i in range(10):
        line_rel(10, 0)
        move_rel(20, 0)
    pause()
    close_graph()

easy_run(main)
Approximate a function curve

Sometimes we need to draw line segments successively.

For example, to plot the function f(x)=sin(x)’s curve on [-3,3] ,we can use many successive line segements to approximate the curve:

  1. divide [-3,3] into n equal intervals, to get n+1 values evenly distributed on [-3,3]: x0,x1,x2,x3,…,xn, and x0=-3, xn=3
  2. cacluate function values f(x0),f(x1),f(x2),f(x3), …, f(xn).
  3. draw n line segements: (x0,f(x0)) to (x1,f(x1)), (x1,f(x1)) to (x2,f(x2)) …, (xn-1,f(xn-1)) to (xn,f(xn))
  4. the resulting line segments is the curve approximation we need.

Apparently, the more greater n is, the more precisely the appoximation is. To minimize the usage of memory, we should calculate and draw the line segments one by one.

The following program plot a sin(x) curve on [-3,3].

from easygraphics import *
import math as m

def main():
    init_graph(600, 400)
    translate(300, 200)  # move origin to the center
    scale(100, -100)  # zoom each axis 100 times, and make y-axis grow from bottom to top.

    x = -3
    delta = 0.01
    move_to(x, m.sin(x))
    while x <= 3:
        line_to(x, m.sin(x))
        x = x + delta
    pause()
    close_graph()

easy_run(main)

Drawing Shapes

Three Types of Drawing Functions

In EasyGraphics, there are three types of functions to draw shapes:

  • Functions that only draw shape outlines. These functions are named like ‘xxx()’ (“xxx” is the shape’s name). The example below draw a circle with a blue outline.
from easygraphics import *

def main():
    init_graph(200, 150)
    set_color(Color.BLUE)
    set_fill_color(Color.RED)
    circle(100, 75, 60)
    pause()
    close_graph()

easy_run(main)
  • Functions that both draw and fill a shape. These functions are named like ‘draw_xxx()’(“xxx” is the shape’s name). The example below draw a red circle with a blue outline.
from easygraphics import *

def main():
    init_graph(200, 150)
    set_color(Color.BLUE)
    set_fill_color(Color.RED)
    draw_circle(100, 75, 60)
    pause()
    close_graph()

easy_run(main)
  • Functions that only fill a shape. These functions are named like ‘fill_xxx()’( “xxx” is the shape’s name). The example below draw a red circle without outline.
from easygraphics import *

def main():
    init_graph(200, 150)
    set_color(Color.BLUE)
    set_fill_color(Color.RED)
    fill_circle(100, 75, 60)
    pause()
    close_graph()

easy_run(main)
circle draw_circle fill_circle
circle() draw_circle() fill_circle()
Angle

In easygraphics, all angles use degree as the unit.

When drawing arc,pie and chords, positive values for the angles mean counter-clockwise while negative values mean the clockwise direction. Zero degrees is at the 3 o’clock position.

The following program draws a pie from 45 degree to 135 degree.

from easygraphics import *

def main():
    init_graph(400, 300)
    set_color("red")
    set_fill_color("lightyellow")
    draw_pie(200, 150, 45, 135, 100, 70)
    pause()
    close_graph()

easy_run(main)
_images/04_pie.png
Polygon

Use polygon()/draw_polygon()/fill_polygon(), we can draw and fill polygons.

To draw a polygon, we should specify the vertices.

polygon()/draw_polygon()/fill_polygon() expect a list as the verticis’ postions. In the list, each vertex is represented as 2 values (x and y). So n vertices is represented by a list with 2n values.

The following example draws a triangle with vertices at (50, 50), (350, 250), (50, 150):

from easygraphics import *

def main():
    init_graph(400, 300)
    set_color(Color.DARK_BLUE)
    set_fill_color(Color.LIGHT_MAGENTA)
    draw_polygon(50, 50, 350, 250, 50, 150)
    pause()
    close_graph()

easy_run(main)
_images/04_polygon.png
Polylines

Using poly_line() or draw_poly_line(), we can draw polylines.

_images/polyline.gif

A polyline is a continuous line composed of one or more line segments. So to draw a polyline, we should specify the endpoints connecting each line segment.

poly_line() and draw_poly_line() expect a list as the endpoint’s postions. In the list, each endpoint is represented as 2 values (x and y). So n endpoints is represented by a list with 2n values.

The following example draws a polyline connecting (50,50), (350,75), (50,150), (350,175), (50,250), (350,275).

from easygraphics import *

def main():
    init_graph(400, 300)
    draw_poly_line(50, 50, 350, 75, 50, 150, 350, 175, 50, 250, 350, 275)
    pause()
    close_graph()

easy_run(main)
_images/04_polyline.png
Bézier curve

A Bézier curve is a parametric curve that uses the Bernstein polynomials as a basis.

A Bézier curve is defined by a set of control points P0 through Pn, where n is called its order (n = 1 for linear, 2 for quadratic, 3 for cubic etc.). The first and last control points are always the end points of the curve; however, the intermediate control points (if any) generally do not lie on the curve.

Cubic Bézier curves are the mostly used Bézier curves.

_images/bezier_curve.png

Four points P0, P1, P2 and P3 in the plane or in higher-dimensional space define a cubic Bézier curve. The curve starts at P0 going toward P1 and arrives at P3 coming from the direction of P2. Usually, it will not pass through P1 or P2; these points are only there to provide directional information. The distance between P1 and P2 determines “how far” and “how fast” the curve moves towards P1 before turning towards P2.

The explicit form of the curve is:

_images/bezier_curve_formula.svg

We can use bezier() or draw_bezier() to draw cubic Bézier curves. They expect a list as the control points’ postions. In the list, each control point is represented as 2 values (x and y). Because a cubic Bézier curve needs 4 control points, so there should be 8 values in the list.

The following program draw a cubic bezier curve with control points at (300,50),(200,50),(200,200) and (100,200).

from easygraphics import *

def main():
    init_graph(600, 400)
    points = [300, 50, 200, 50, 200, 200, 100, 200]
    draw_bezier(*points)
    pause()
    close_graph()

easy_run(main)

We can use quadratic() or draw_quadratic() to draw quadratic Bézier curves. They expect a list as the control points’ postions. In the list, each control point is represented as 2 values (x and y). Because a quadratic Bézier curve needs 3 control points, so there should be 6 values in the list.

The following program draw a quadratic bezier curve with control points at (300,50),(200,50) and (100,200).

from easygraphics import *

def main():
    init_graph(600, 400)
    points = [300, 50, 200, 50, 100, 200]
    draw_quadratic(*points)
    pause()
    close_graph()

easy_run(main)
Flood Fill

Non-regular shapes can be filled by flood fill. The shape to be filled must be enclosed by an outline. The follow program uses flood fill to fill a petal.

from easygraphics import *

def main():
    init_graph(400, 200)
    arc(200, -40, 180, 360, 220, 220)
    arc(200, 240, 0, 180, 220, 220)
    set_fill_color(Color.DARK_RED)
    flood_fill(200, 100, Color.BLACK)
    pause()
    close_graph()

easy_run(main)

Below is the result:

_images/04_pedal.png
Fill Rule

Fill rule controls how non-convex shapes are filled.

_images/04_fill_rule.png

You can use set_fill_rule() to change the fill rule.

The default fill rule is odd even fill.

from easygraphics import *

def main():
    init_graph(420, 200)

    set_fill_rule(FillRule.ODD_EVEN_FILL)
    set_fill_color("lightgray")
    draw_polygon(50, 50, 150, 50, 60, 110, 100, 20, 140,110,50,50)

    draw_text(5,150,"FillRule.ODD_EVEN_FILL")

    translate(220,0)

    set_fill_rule(FillRule.WINDING_FILL)
    set_fill_color("lightgray")
    draw_polygon(50, 50, 150, 50, 60, 110, 100, 20, 140,110,50,50)

    draw_text(5,150,"FillRule.WINDING_FILL")

    pause()
    close_graph()

easy_run(main)
Advanced Drawing

EasyGraphics supports drawing all the basic shape: point, line, circle, ellipse, rectangle, polygon, rectangle with rounded corner, etc. If you need more advanced drawing, you can use Image object’s get_painter() method to get the QPainter instance and draw.

Drawing a Shape using Vertices

We can use vertices to draw complex shapes.

The following code draws a star.

Note:

  • We use a for loop to define 5 vertices of the star.
  • We set end_shape()’s parameter to True to draw a closed polyline. If you want a polyline that not closed, use end_shape()’s default False parameter.
  • If you don’t want fill, you should not close the shape, or you can set the fill color to Color.TRANSPARENT
from easygraphics import *

def main():
    init_graph(400,300)
    set_color(Color.BLACK)
    set_fill_color(Color.LIGHT_GRAY)
    # set the axis origin to (200,150)
    translate(200, 150)
    begin_shape()
    for i in range(5):
        vertex(0,-100)
        rotate(144)
    end_shape(True)
    pause()
    close_graph()

easy_run(main)
_images/05_1_vertices_1.png

Let’s see what happens if we don’t close the shape:

from easygraphics import *

def main():
    init_graph(400,300)
    set_color(Color.BLACK)
    set_fill_color(Color.LIGHT_GRAY)
    # set the axis origin to (200,150)
    translate(200, 150)
    begin_shape()
    for i in range(5):
        vertex(0,-100)
        rotate(144)
    end_shape()
    pause()
    close_graph()

easy_run(main)
_images/05_1_vertices_2.png
Spline Curve (Catmull-Rom Curve)

We can use vertices to draw a spline curve (Catmull-Rom curve).

from easygraphics import *

def main():
    init_graph(200,200)
    set_color(Color.BLACK)
    set_fill_color(Color.LIGHT_GRAY)
    points = [(40,40),
              (80,60),
              (100,100),
              (60,120),
              (50,150)]

    # draw the curve
    begin_shape()
    curve_vertex(40,40) # the first control point is also the start point of the curve
    for point in points:
        curve_vertex(point[0],point[1])
    curve_vertex(50,150) # the last control point is also the end point of the curve
    end_shape()

    # draw control points
    set_fill_color(Color.RED)
    for point in points:
        fill_circle(point[0],point[1],3)

    pause()
    close_graph()

easy_run(main)
_images/05_1_curve_2.png

See what happens if we close the shape.

from easygraphics import *

def main():
    init_graph(200,200)
    set_color(Color.BLACK)
    set_fill_color(Color.LIGHT_GRAY)
    points = [(40,40),
              (80,60),
              (100,100),
              (60,120),
              (50,150)]

    # draw the curve
    begin_shape()
    curve_vertex(40,40) # the first control point is also the start point of the curve
    for point in points:
        curve_vertex(point[0],point[1])
    curve_vertex(50,150) # the last control point is also the end point of the curve
    end_shape(True)

    # draw control points
    set_fill_color(Color.RED)
    for point in points:
        fill_circle(point[0],point[1],3)

    pause()
    close_graph()

easy_run(main)
_images/05_1_curve_1.png
Bezier Curve

The following code use vertices to draw a cubic bezier curve.

from easygraphics import *

def main():
    init_graph(200,200)

    #draw bezier curves
    set_color("black")
    set_fill_color("yellow")
    begin_shape()
    vertex(30, 70) # first point
    bezier_vertex(25, 25, 100, 50, 50, 100)
    bezier_vertex(20, 130, 75, 140, 120, 120)
    end_shape()

    # draw control lines
    set_color("lightgray")
    line(30,70,25,25)
    line(100,50,50,100)

    line(50,100,20,130)
    line(75,40,120,120)

    # draw control points
    set_fill_color("red")
    fill_circle(30,70,3)
    fill_circle(25,25,3)
    fill_circle(100,50,3)

    set_fill_color("blue")
    fill_circle(50,100,3)
    fill_circle(20,130,3)
    fill_circle(75,40,3)
    fill_circle(120,120,3)

    pause()
    close_graph()

easy_run(main)
_images/05_1_bezier_1.png

Line Styles

Using line styles, you can control how the lines and outlines are drawn. The most useful line styles are:

  • line width
  • line shape
Line Width

You can use set_line_width()/get_line_width() to get or set line width.

The following program draws a rectangle whose borders width is 10.

from easygraphics import *

def main():
    init_graph(400, 300)
    set_line_width(10)
    draw_rect(50, 50, 350, 250)
    pause()
    close_graph()

easy_run(main)
Predefined Line Shapes

Using line shapes, you can draw dash line or dot line. Use set_line_style()/get_line_style() to set line shape.

solid_line dash_line dot_line
LineStyle.SOLID_LINE LineStyle.DASH_LINE LineStyle.DOT_LINE
dash_dot_line dash_dot_dot_line no_pen
LineStyle.DASH_DOT_LINE LineStyle.DASH_DOT_DOT_LINE LineStyle.NO_PEN

The following program draws a rectangle with dash outlines.

from easygraphics import *

def main():
    init_graph(400, 300)
    set_line_width(10)
    set_line_style(LineStyle.DASH_LINE)
    draw_rect(50, 50, 350, 250)
    pause()
    close_graph()

easy_run(main)
Custom Line Shapes

If predefined line shapes is not satisfying, you can set custome line shape. To do this, you should:

  1. use get_target() or create_image() to get the Image object you want to draw.
  2. use the Image object’s get_pen() to get the pen. It’s a PyQt’s QPen object.
  3. Use the pen’s setDashPattern() to set custom line shape.
from easygraphics import *

def main():
    init_graph(400, 300)
    set_line_width(10)
    target_image = get_target()
    pen = target_image.get_pen()
    pen.setDashPattern([1, 5, 2, 5])
    draw_rect(50, 50, 350, 250)
    pause()
    close_graph()

easy_run(main)
More Line Styles

After getting the pen object, you can set other pen attributes to get more line styles. See QPen’s documentation.

Drawing Text

Use draw_text() and draw_rect_text() functions, we can draw text.

These functions works like print(), you can provide many objects to draw in one function call:

from easygraphics import *

def main():
    init_graph(400, 50)
    draw_text(50, 30, "There", "are", 5, "dogs", "under", "the", "tree", ".")
    pause()
    close_graph()

easy_run(main)

Running the program above will get the follow result:

_images/07_hello.png

If you want to use seperators instead of space, just provide the “sep” parameter:

from easygraphics import *

def main():
    init_graph(400, 50)
    draw_text(50, 30, "There", "are", 5, "dogs", "under", "the", "tree", ".", sep=",")
    pause()
    close_graph()

easy_run(main)

The result of the above program is:

_images/07_custom_pos.png
Drawing Positions

In draw_text(), the first 2 paramenter (x,y) specify the start drawing position of the text. This start position is left-bottom corner of the text’s out border.

So the following code will draw text out of the graphics window:

from easygraphics import *

def main():
    init_graph(500, 200)
    draw_text(50, 0, "Hello world!")
    pause()
    close_graph()

easy_run(main)
Drawing Text in the Specified Rectangle

Using draw_rect_text(), we can draw a text in a bounded rectangle.

Note that the first 2 parameters (left,top) is the bounding rectangle’s left-top corner, and the 3rd and 4th parameters (width, height) is the bounding rectangle’s width and height.

You can use flags to control text alignment in the rectangle.

If the bound rectangle is not big enough to enclose the whole text, the text will be clipped.

If flag “TextFlags.TEXT_WORD_WRAP” is set, the text will auto wrap if it is too long to hold in one line.

from easygraphics import *

def main():
    init_graph(400, 300)
    draw_rect(50, 50, 350, 250)  # draw a border to better see the result
    draw_rect_text(50, 50, 300, 200, "There are so many beautiful flowers in the garden!",
                   flags=TextFlags.TEXT_WORD_WRAP | TextFlags.ALIGN_CENTER)
    pause()
    close_graph()

easy_run(main)

Following is the result of the above program. Note that we use draw_rect() to draw a border around the bounding rect to better show effect of the flags.

_images/07_multilines.png

View Port and the Logical Window

Normally we just paint on the whole image or window. But sometimes it will be more convenient to paint relatively in a portion of the image. We can use view port to achieve this.

In some cases we want to zoom the painting, or set the origin to some place other than the view port’s top-left cornert. We can use the logical window to achieve this.

View Port

View port controls which portion of the image (the graphics window) we are drawing at.

The following program draws 3 circles on the graphics window. Pay attention to their positions.

from easygraphics import *

def main():
    init_graph(400, 300)
    circle(100, 100, 50)
    circle(100, 100, 100)
    circle(100, 100, 120)
    pause()
    close_graph()

easy_run(main)
_images/08_without_view_port.png

The following program set view port to the rectangle from (100,50) to (300,250), then draw 3 circles with the code as the above programming. Compare the result with the above program. Note that we draw a border around the view port to better see effect of the clipping.

from easygraphics import *

def main():
    init_graph(400, 300)
    set_color("lightgray")
    draw_rect(100, 50, 300, 250)
    set_color("black")

    set_view_port(100, 50, 300, 250)
    circle(100, 100, 50)
    circle(100, 100, 100)
    circle(100, 100, 120)
    pause()
    close_graph()

easy_run(main)
_images/08_with_clip.png

In the above example, all drawings outside the view port is not painted (is clipped). We can turn off this feature by set the “clip” parameter to False:

from easygraphics import *

def main():
    init_graph(400, 300)
    set_color("lightgray")
    draw_rect(100, 50, 300, 250)
    set_color("black")

    set_view_port(100, 50, 300, 250, clip=False)
    circle(100, 100, 50)
    circle(100, 100, 100)
    circle(100, 100, 120)
    pause()
    close_graph()

easy_run(main)
_images/08_without_clip.png
The Logical Window

In easygraphics ( and the qt underlying) , there are 2 coordinates, the logical coordinates and the physical coordinates.

The physical coordinates is the coordinate on the drawing device ( the graphics window or an Image object). (0,0) is always at the device’s top-left corner, and x-axis grows from left to right, y-axis grows from top to bottom.

The logical coordinates is the coordinate we are using when specifying drawing parameters. That is, when we call circle(50,50,100), the circle’s center (50,50) is a logical coordinate.

Easygraphics will translate the logical coordinates to the physical coordinates when drawing. By default, the logical coordinates and the physical coordinates coincide. The view port and window will affect how the logical coordinates are translated.

Qt’s document explains how the coordinates are translated.

The following example move the logical origin to the center, and zoom the drawing 100 times on x and y axis:

  • the default view port is 600 width, 400 height. and the window is 6 width, 4 height, so on x-axis we gets 600/6=100 times zoom, and on y-axis we gets 400/4=100 times zoom.
  • the window is 6 width, 4 height, and we put the left-top corner at (-3,-2), so we get (0,0) at the center.
from easygraphics import *

def main():
    init_graph(600, 400)
    set_window(-3, -2, 6, 4)

    circle(0, 0, 1.5)
    pause()
    close_graph()

easy_run(main)
_images/08_window.png

Note: Obviously the logical window is difficult to understand and use. We can use transform to achieve the same result.

Transforms

Easygraphics (and the underlying Qt system) support 5 basic coordinate transform operations:

  • Translation: moves every point of a figure or a space by the same distance in a given direction.
  • Rotation: the motion of a rigid body around a fixed point
  • Scaling :enlarges (increases) or shrinks (diminishes) objects by a separate scale factor for each axis direction.
  • Shear Mapping(Skew) : a linear map that displaces each point in fixed direction, by an amount proportional to its signed distance from a line that is parallel to that direction.
  • Relection (Flipping): a transformation in geometry in which an object is reflected in a line to form a mirror image.

The following code draws a simple bus. We’ll use it as the basis for this chapter’s examples.

def draw_bus():
    """
    Draw a simple bus
    """
    set_color("lightgray")
    rect(60, 20, 270, 150)

    set_color("red")
    set_fill_color("blue")

    draw_circle(120, 120, 10)  # draw tyre
    draw_circle(200, 120, 10)  # draw tyre
    rect(80,40,250,120)

    # draw window
    x = 90
    while x < 175 :
        rect(x, 60, x+10, 70)
        x += 15

    # draw door
    rect(220, 60, 240, 120);
    line(230, 60, 230, 120);
    circle(230, 90, 5);

The following program draws a un-transformed bus:

from easygraphics import *
import draw_bus


def main():
    init_graph(500, 300)
    draw_bus.draw_bus()
    pause()
    close_graph()

easy_run(main)
_images/09_no_transform.png
Translation

Translation is the most commonly used transformation. It moves each point by offset_x on x-axis, and offset_y on y-axis. We use it to move the origin’s position ( and the whole drawing).

The following program use translate() to move the origin to the center of the graphics window, then draw the bus.

from easygraphics import *
import draw_bus

def main():
    init_graph(500, 300)
    translate(250, 150)
    draw_bus.draw_bus()
    pause()
    close_graph()

easy_run(main)
_images/09_translation.png

Note: set_origin() is an alias of translate()

Rotation

Use rotate() to rotate the coordinate around the point (x,y) clockwise.

Note: the angle directions in rotate() and in shape functions (i.e. draw_pie()) are opposite!

If you need a counter-clockwise rotation, just give a negative rotation degree.

The following program draws a bus rotated 45 degree counter-clockwise around it’s center (105,65).

from easygraphics import *
import draw_bus

def main():
    init_graph(500, 300)
    # rotate around the (105,65)
    rotate(-45, 105, 65)

    draw_bus.draw_bus()
    pause()
    close_graph()

easy_run(main)
_images/09_rotation.png
Scaling

We can use scale() to scale the drawing in x and y axis separately.

The following program draws a x-axis shrinked and y-axis enlarged bus.

from easygraphics import *
import draw_bus

def main():
    init_graph(500, 300)

    scale(0.5, 2)
    draw_bus.draw_bus()

    pause()
    close_graph()

easy_run(main)
_images/09_scale.png
Shear Mapping (Skew)

We use shear() or its alias skew to shear a drawing around the center. shear() needs 2 parameters “sv” and “sh”. After shearing, each point (x,y) is transformed to (x+sh*y, y+sv*x). We can see its effect by the following examples.

Shear on X-axis

In the follow example, we shear the bus along the x-axis. Note that the default y-axis is from top to bottom.

from easygraphics import *
import draw_bus

def main():
    init_graph(500, 300)

    shear(0.5, 0)
    draw_bus.draw_bus()

    pause()
    close_graph()

easy_run(main)
_images/09_skew_x.png
Shear on Y-axis

In the follow example, we shear the bus along the y-axis.

from easygraphics import *
import draw_bus


def main():
    init_graph(500, 300)

    shear(0, 0.5)
    draw_bus.draw_bus()

    pause()
    close_graph()

easy_run(main)
_images/09_skew_y.png
Shear on both axis

In the follow example, we shear the bus along the x and y-axis at the same time.

from easygraphics import *
import draw_bus

def main():
    init_graph(500, 300)

    shear(0.5, 0.5)
    draw_bus.draw_bus()

    pause()
    close_graph()

easy_run(main)
_images/09_skew.png
Reflection (Mirror, Flipping)

We can use reflect() ( or its alias mirror() and flip() ) to do a reflection. It reflect the drawing again the line passing its parameters (x1,y1) and (x,y).

Reflection against the y-axis

The following program flip the bus horizontally ( reflection against the bus’s vertical center line x=105 ) :

from easygraphics import *
import draw_bus

def main():
    init_graph(500, 300)
    reflect(105, 0, 105, 1)
    draw_bus.draw_bus()
    pause()
    close_graph()

easy_run(main)
_images/09_flip_h.png
Reflection against the x-axis

The following program flip the bus vertically ( reflection against the bus’s horizontal center line y=65 ) :

from easygraphics import *
import draw_bus

def main():
    init_graph(500, 300)

    reflect(0, 65, 1, 65)

    draw_bus.draw_bus()
    pause()
    close_graph()

easy_run(main)
_images/09_flip_v.png
Reflection against other lines

The following program flip the bus against the line passing (0, 300) and (500,0). To clearly see the result, we first draw a non-transformed bus, a mirror line, then draw the flipped bus.

from easygraphics import *
import draw_bus

def main():
    init_graph(500, 300)

    draw_bus.draw_bus()

    set_color("gray")
    set_line_style(LineStyle.DASH_LINE)
    line(0, 300, 500, 0)
    set_line_style(LineStyle.SOLID_LINE)

    reflect(0, 300, 500, 0)
    draw_bus.draw_bus()
    pause()
    close_graph()

easy_run(main)
_images/09_flip.png
Compound Transforms

Transforms can be compounded.

In the following example, we first translate the origin to the image center, then rotate the bus around its center, then shear it around its center, then scale it by a factor of 1.2 .

from easygraphics import *
import draw_bus

def main():
    init_graph(500, 300)

    # move the origin to the center of the image
    translate(250, 150)

    # rotate around the bus center
    translate(105, 65)
    rotate(180)
    translate(-105, -65)

    # shear arount the bus center
    translate(105, 65)
    shear(0.5, 0.5)
    translate(-105, -65)

    # scale
    scale(1.2, 1.2)
    draw_bus.draw_bus()
    pause()
    close_graph()

easy_run(main)
_images/09_compound.png
Drawing with Y-Axis Grows Bottom-Up

You may have noticed that when you reflect the image, the texts drawing on the image will also get reflected. When what you want is to draw on an ordinary coordinate system whose Y-axis grows bottom-up, this will not be what you what.

Easygraphics provides a set_flip_y() function to used in this situation.

Also notice that if you turn on the set_flip_y(), all the angles parameters used in the drawing functions should be mirrored too. That is, if the docs said a positive angle means turn clock-wise, after the set_flip_y() is on, a positive angle will mean turn counter-clockwise.

Compare the following two programs. The first one use set_flip_y() to make y-axis grows bottom-up; and the second one use reflect(1,0) to do that job. See the results.

Use set_flip_y() to make y-axis grows bottom-up:

from easygraphics import *
import draw_bus

def main():
    init_graph(500, 300)

    translate(250, 150)
    translate(105, 65)
    rotate(-45)
    translate(-105, -65)

    set_flip_y(True)
    # reflect(1,0)

    translate(105, -65)
    shear(0.2, 0.2)
    translate(-105, 65)

    draw_bus.draw_bus()
    set_color("blue")
    draw_rect_text(0, 0, 210, 130, "This is a very good day!")
    pause()
    close_graph()

easy_run(main)
_images/09_y_set.png

Use reflect(1,0) to make y-axis grows bottom-up:

from easygraphics import *
import draw_bus

def main():
    init_graph(500, 300)

    translate(250, 150)
    translate(105,65)
    rotate(-45)
    translate(-105,-65)

    reflect(1,0)

    translate(105, -65)
    shear(0.2,0.2)
    translate(-105, 65)

    draw_bus.draw_bus()
    set_color("blue")
    draw_rect_text(0,0,210,130,"This is a very good day!")
    pause()
    close_graph()

easy_run(main)
_images/09_y_reflect.png

Compositions

When we are drawing , what we really do is to change the destination pixels color. Instead of just using (copy) the source color, the color be decided by both the source and the destination’s (old) color. This is where the composition modes come in.

Easygraphics (and the underlying Qt system) support three types of compositions:

  • Bit Blit ( Raster Operation (ROP) / Bitwise Operation ): the source color and the destination color are combined using a boolean function. Both the source color and the destination color must be opaque.
  • Alpha compositing : is the process of combining the source with the destination to create the appearance of partial or full transparency.
  • Blend : is used in digital image editing and computer graphics to determine how two layers are blended into each other.

These three types is not strictly orthogonal, and some compositions have different names in each type.

Bit Blit (Raster Operations)

Bit Blit is the classic composition operation used in old graphic systems. Because it requires both the source color and the destination color to be opaque, it’s of limited use in modern graphics systems.

A classic usage of the raster operation is using bitwise XOR to draw and clear a shape, so as to create an animation.

The following example use bitwise XOR to draw and clear the ellipse. Note that other colors will not do the job.

from easygraphics import *

def main():
    init_graph(400, 200)
    set_render_mode(RenderMode.RENDER_MANUAL)
    set_background_color("white")
    x = 100
    ellipse(x, 100, 100, 50)  # draw a ellipse
    set_color("white")
    set_composition_mode(CompositionMode.SRC_XOR_DEST)
    while is_run():
        old_x = x
        x = (x + 5) % 400
        ellipse(old_x, 100, 100, 50)  # clear the ellipse last drawn
        ellipse(x, 100, 100, 50)  # draw a new ellipse
        delay_fps(30)

    close_graph()

easy_run(main)
Alpha Compositing

Alpha Compositing is the mostly used composition type.

The following table shows the result of the alpha compositings.

Source and Source Over is the mostly used compistings.

Source and Destination are opaque source_o source_over_o source_in_o
  Source Source Over source in
  source_out_o source_atop_o xor_o
  source out source atop xor
  destination_o destination_over_o destination_in_o
  Destination Destination Over Destination in
  destination_out_o destination_atop_o xor_o
  Destination out Destination atop xor
Source and Destination are partially transparent source_t source_over_t source_in_t
  Source Source Over source in
  source_out_t source_atop_t xor_t
  source out source atop xor
  destination_t destination_over_t destination_in_t
  Destination Destination Over Destination in
  destination_out_t destination_atop_t xor_t
  Destination out Destination atop xor
Blend

Blend is mainly used for image or photo processing. See wikipedia for more details about it.

Image Processing

Sometimes we need to paint a complicated drawing repeatedly. It will be very cumbersome and time consuming if we start the drawing from scratch each time. A better solution is to first draw it on a seperate image, and reuse the image.

Create and Draw on a Image

Use create_image() to create a new image instance.

There are two ways to draw on a image:

  1. the OOP way: Use the image’s method. The image created by create_image() is an Image object. we can use it’s method directly.
img=create_image(800,600)
img.draw_circle(100,100,50)
  1. the traditional way: Use the drawing functions mentioned in the previous chapters, and provide the image as an additional parameter.
img=create_image(400,300)
draw_circle(100,100,50,img)
The Graphics Window and The Drawing Target

In Easygraphics, the graphics window is just a special image.

To easy the coding, Easygraphics has a target image property. Most of the drawing functions has an optional paramter “image” or “dst_image”, if it’s not provided, the target image will be where the drawing happens. By default the target image is setting to the graphics window.

So you call drawing functions without specifying which image is to draw, the graphics window will get drawn.

You can use set_target() to change the drawing target, and use get_target() to get the drawing target.

the following code use set_target() to change drawing target to a image, and draw on it:

Note: Remember to use close_image() to close the unused images.
img=create_image(400,300)
set_target(img)
draw_circle(100,100,50)
Saving Image

We can use save_image() to save a image to the disk.

The following program draw a bus and save it to “bus_screen.png” in the current folder.

Note that because:

  1. By default save_image() will save the drawing target image;
  2. By default the target image is the graphics window.

So we are saving the graphics window.

from easygraphics import *
import draw_bus

def main():
    init_graph(600,400)
    draw_bus.draw_bus()
    save_image("bus_screen.png")
    pause()
    close_graph()

easy_run(main)
Copy Image

We can use draw_image() to copy part of one image to another image.

In the following example, we:

  1. create a image and save it to variable “img”
  2. set drawing target to “img”
  3. draw a bus to “img” (the drawing target)
  4. set drawing target back to the graphics window
  5. copy the content on “img” to the graphics window’s different positions.
from easygraphics import *
import draw_bus

def main():
    init_graph(750, 450)
    img = create_image(210, 130)
    set_target(img)  # set target to img
    draw_bus.draw_bus()
    set_target()  # set target back to the graphics window
    set_background_color("black")
    for i in range(0, 9):
        x = i % 3 * 250
        y = i // 3 * 150
        draw_image(x + 20, y + 10, img)

    pause()
    img.close()
    close_graph()

easy_run(main)

The result:

_images/11_copy_buses.png
Image Transparency and Composition Mode

put_image() copy a rectangle area to the destination image. If you want to copy things that are not rectanglely outlined, you can draw it on a image with fully transparent background, then copy

The following example is identical to the above example, expect that it set the source image’s background to transparent before drawing the bus.

from easygraphics import *
import draw_bus

def main():
    init_graph(750, 450)
    img = create_image(210, 130)
    set_background_color(Color.TRANSPARENT, img)  # set img's background to transparency
    set_target(img)  # set target to img
    draw_bus.draw_bus()
    set_target()  # set target back to the graphics window
    set_background_color("black")
    for i in range(0, 9):
        x = i % 3 * 250
        y = i // 3 * 150
        draw_image(x + 20, y + 10, img)

    pause()
    img.close()
    close_graph()

easy_run(main)

The result is :

_images/11_copy_bus_trans.png
Copy Image without the Background

If you can’t draw with a transparent background, you can copy the image without the background, by set the parameter “with_background” to False.

In the following example, we don’t use a transparent backround, and we do the copy without background.

from easygraphics import *
import draw_bus

def main():
    init_graph(750, 450)
    img = create_image(210, 130)
    set_target(img)  # set target to img
    draw_bus.draw_bus()
    set_target()  # set target back to the graphics window
    set_background_color("black")
    for i in range(0, 9):
        x = i % 3 * 250
        y = i // 3 * 150
        draw_image(x + 20, y + 10, img, with_background=False)

    pause()
    img.close()
    close_graph()

easy_run(main)
_images/11_copy_bus_trans.png
Copy Image with transforms

If you want to copy a image with transforms such as rotation, you should set the transforms before the copy.

The following program copy images with rotation. Note the use of save_settings() and restore_settings(), we use it to save and restore image’s transforms.

Note: It’s a good practice to save the old transfrom before doing any transforms before copy, and restore the old settings after the copy.
from easygraphics import *
import draw_bus

def main():
    init_graph(750, 450)
    img = create_image(210, 130)
    set_target(img)  # set target to img
    draw_bus.draw_bus()
    set_target()  # set target back to the graphics window
    set_background_color("black")
    for i in range(0, 9):
        x = i % 3 * 250 + 20
        y = i // 3 * 150 + 10
        save_settings()
        # transforms
        translate(x, y)
        translate(105, 65)
        rotate(45)
        translate(-105, -65)

        draw_image(0, 0, img, with_background=False)
        restore_settings()
    pause()
    img.close()
    close_graph()

easy_run(main)
_images/11_copy_bus_transform.png
Load Image

We can load image from files.

Note: JPEG format doesn’t support transparency. So use the PNG format if you want to save and load image with transparent backgrounds.

The following example load and display a image.

from easygraphics import *

def main():
    init_graph(800, 600)
    img = load_image("test.png")
    draw_image((get_width() - img.get_width()) // 2,
               (get_height() - img.get_height()) // 2, img)
    pause()
    img.close()
    close_graph()

easy_run(main)
Headless Mode

Sometimes we just want to draw and save the image, and don’t need to display it on the screen. Easygraphics provides a headless mode to do the jobs. In this mode, no graphics window is displayed, and functions for animations such as pause() won’t work.

The following program shows how to use init_graph() to create a headless mode.

from easygraphics import *
import draw_bus

def main():
    init_graph(headless=True)
    img = create_image(210, 130)
    set_target(img)
    draw_bus.draw_bus()
    save_image("headless_bus.png")
    img.close()
    close_graph()

easy_run(main)

Animation

By rapidly changing the painting (frames) on the graphics window, we can make an animation.

Time Control

Because the computer can draw very fast, we must let it to wait some time between two frames.

Note: Functions used in this section won’t work in the headless mode.

In easygraphics, we can use delay() to pause the program from the specified milliseconds.

Control the FPS

Because the actual drawing time can be different each time drawing, a better way to control the speed is by using the delay_fps() function.

FPS is the abbreviation of “frames per second”.delay_fps() will calculate each frame’s drawing time, and wait to make each frame displays evenly.

Render Mode

There are two render mode in EasyGraphics:

  1. RenderMode.AUTO: All drawings on the graphics window will show immediately. This is the default mode, and is for normal drawing.
  2. RenderMode.Manual: Drawings will not show on the graphics window. Only time control, keyboard or mouse functions like pause()/delay()/delay_fps()/get_mouse_msg() will update the graphics window. This mode can speed up the animation frames drawing.

It’s a good practice to set the render mode to manual when your want to show an animation.

You can use set_render_mode() to set the render mode.

Note: If you are not drawing on the graphics window, this render mode has no effect.
Background

Ofter we need to make an object move in a background. If the background is complicated, it’s not a good idea to recreate the background in each frame.

A common solution is to draw background in one image , and the moving object in another transparent image. The final result is made by merging the two images.

The following program draws a moving bus on the road (background).Note the use of the is_run() function.

from easygraphics import *

def main():
    init_graph(800, 600)
    set_render_mode(RenderMode.RENDER_MANUAL)

    background = create_image(800, 600)
    set_target(background)
    set_background_color(Color.LIGHT_YELLOW)
    set_fill_color(Color.RED)
    draw_circle(150, 150, 50)
    set_fill_color(Color.DARK_BLUE)
    draw_rect(0, 400, 800, 600)

    car = create_image(162, 150)
    set_target(car)
    set_composition_mode(CompositionMode.SOURCE)
    set_background_color(Color.TRANSPARENT)
    set_fill_color("white")
    draw_polygon(0, 0, 0, 60, 160, 60, 160, 40, 125, 20, 110, 0)
    set_fill_color("darkgray")
    draw_circle(35, 60, 20)
    draw_circle(120, 60, 20)
    set_fill_color("transparent")
    draw_rect(10, 10, 40, 25)
    draw_rect(50, 10, 80, 25)

    set_target()
    x = 0
    while is_run():
        x = (x + 2) % 750
        draw_image(0, 0, background)
        draw_image(x, 350, car)
        delay_fps(100)

    background.close()
    car.close()
    close_graph()

easy_run(main)
Skipping Frames

Sometimes a drawing can be complicated and slow, and we can’t finish a frame drawing in the specified frame time. This will create lags in the animation.

The delay_jfps() can skip some frames ( if a frame is using too much time, the successive frames will be skipped to keep up with the specified fps).

The following example shows how to use delay_jfps() to control time. Note that we use sleep() to simulate a long-time drawing operation.

from easygraphics import *
import time

def main():
    init_graph(640, 480)
    set_color(Color.BLUE)
    set_fill_color(Color.GREEN)
    set_render_mode(RenderMode.RENDER_MANUAL)

    x = 0
    while is_run():
        x = (x + 1) % 440
        if delay_jfps(60, 0):
            clear_device()
            draw_ellipse(x + 100, 200, 100, 100)
            time.sleep(0.5)
    close_graph()
easy_run(main)

Mouse and Keyboard

Often we need to get input from the user in the programs. Easygrphics provides simple ways to get user’s input from keyboard and mouse.

Pause for input

The most used user input function in Easygraphics is pause(). This function pause the program, and wait for user to click on the graphics window, or press any key, then continue the program.

Mouse Clicking

We can use get_click() to pause the program and wait for a mouse clicking. This function will return the x,y coordinates of the position clicked, and buttons that are pressed when clicking.

from easygraphics import *

def main():
    init_graph(800, 600)
    set_render_mode(RenderMode.RENDER_MANUAL)

    while is_run():
        msg = get_click()
        str = "clicked on %d,%d ." % (msg.x, msg.y)
        clear_device()
        draw_text(0, 600, str)

    close_graph()

easy_run(main)
Cursor Positions

Sometimes we need to get the position of the cursor. We can use get_cursor_pos() to get this job done.

The following program continuously displays mouse cursor’s position.

from easygraphics import *

def main():
    init_graph(800, 600)
    set_render_mode(RenderMode.RENDER_MANUAL)

    while is_run():
        x, y = get_cursor_pos()
        clear_device()
        draw_text(0, 600, "%d,%d" % (x, y))
        delay_fps(30)

    close_graph()

easy_run(main)
Mouse Button Press and Release

You can use get_mouse_msg() to get mouse button press and release messages.

Non-Blocking mouse processing

get_click()/get_mouse_msg() will block the program if there are no mouse press/click in the last 100ms. If you want to check the mouse operation non-blockly, you could use the non-blocking function has_mouse_msg() to see if there are any mouse messages, and then use get_mouse_msg() to get the mouse message.

The following program continuously check display cursor’s postion and mouse button press/release events.

from easygraphics import *

def main():
    init_graph(800, 600)
    set_render_mode(RenderMode.RENDER_MANUAL)

    set_fill_color("white")
    while is_run():
        x, y = get_cursor_pos()
        fill_rect(0, 580, 390, 600)
        draw_text(0, 600, "%d,%d" % (x, y))
        if has_mouse_msg():
            msg = get_mouse_msg()
            if msg.type == MouseMessageType.PRESS_MESSAGE:
                typestr = "pressed"
            elif msg.type == MouseMessageType.RELEASE_MESSAGE:
                typestr = "released"
            fill_rect(400, 580, 800, 600)
            draw_text(400, 600, "button %s at %d,%d" % (typestr, x, y))
        delay_fps(30)

    close_graph()

easy_run(main)
Mouse Message Demo

The following program draws a bezier curve interactively

First click on the window to set the first control point of the curve. Then click on the window to set the second control point of the curve. Then drag from any of the above two control points to set the third and the fourth control point.

from easygraphics import *
from PyQt5 import QtCore

def main():
    init_graph(800, 600)
    set_render_mode(RenderMode.RENDER_MANUAL)

    msg = get_click()
    x1=msg.x
    y1=msg.y
    circle(x1, y1, 3)
    msg = get_click()
    x2=msg.x
    y2=msg.y
    circle(x2, y2, 3)
    line(x1, y1, x2, y2)

    x3, y3 = x1, y1
    x4, y4 = x2, y2
    reg1 = QtCore.QRect(x1 - 2, y1 - 2, 5, 5)
    reg2 = QtCore.QRect(x2 - 2, y2 - 2, 5, 5)
    draging_which_point = 0
    while is_run():
        if draging_which_point == 1:
            draw_line(x1, y1, x, y)
            draw_bezier(x1, y1, x, y, x4, y4, x2, y2)
        elif draging_which_point == 2:
            draw_line(x2, y2, x, y)
            draw_bezier(x1, y1, x3, y3, x, y, x2, y2)

        if has_mouse_msg():
            # x, y, type, buttons, modifiers = get_mouse_msg()
            msg = get_mouse_msg()
            if msg.type == MouseMessageType.PRESS_MESSAGE:
                if reg1.contains(msg.x, msg.y):
                    draging_which_point = 1
                    set_color(Color.WHITE)
                    set_composition_mode(CompositionMode.SRC_XOR_DEST)
                    x, y = x3, y3
                elif reg2.contains(msg.x, msg.y):
                    draging_which_point = 2
                    set_color(Color.WHITE)
                    set_composition_mode(CompositionMode.SRC_XOR_DEST)
                    x, y = x4, y4
                else:
                    draging_which_point = 0
            elif msg.type == MouseMessageType.RELEASE_MESSAGE:
                if draging_which_point == 1:
                    x3, y3 = msg.x, msg.y
                elif draging_which_point == 2:
                    x4, y4 = msg.x, msg.y
                draging_which_point = 0

                set_color(Color.BLACK)
                set_composition_mode(CompositionMode.SOURCE)
                clear_device()
                draw_line(x1, y1, x3, y3)
                draw_line(x2, y2, x4, y4)
                circle(x1, y1, 3)
                circle(x2, y2, 3)
                draw_bezier(x1, y1, x3, y3, x4, y4, x2, y2)
        else:
            if draging_which_point == 1:
                x, y = get_cursor_pos()
                draw_line(x1, y1, x, y)
                draw_bezier(x1, y1, x, y, x4, y4, x2, y2)
            elif draging_which_point == 2:
                x, y = get_cursor_pos()
                draw_line(x2, y2, x, y)
                draw_bezier(x1, y1, x3, y3, x, y, x2, y2)
        delay_fps(60)

    close_graph()

easy_run(main)
Char Input

We can use has_kb_hit() to see if there is any ascii char pressed, and use get_char() to get the inputted char. has_kb_hit() is non-blocking, and get_char() is blocking.

The following program is a simple print game.

from easygraphics import *
import random


def show_welcome():
    clear_device()
    set_color("yellow")
    set_font_size(64)
    draw_text(160, 110, "Print Game");
    set_color("white");
    c = 0
    set_font_size(20)
    while is_run():
        if has_kb_hit():
            break
        set_color(color_rgb(c, c, c))
        draw_text(180, 400, "Press any key to continue")
        c = (c + 8) % 255;
        delay_fps(30)
    ch = get_char()
    clear_device()


def show_goodbye():
    clear_device();
    set_color("yellow");
    set_font_size(48);
    draw_text(104, 180, "Bye!!!");
    pause()


def main():
    init_graph(640, 480)
    set_render_mode(RenderMode.RENDER_MANUAL)
    set_background_color("black")

    show_welcome()
    random.seed()
    set_font_size(20)
    set_fill_color("black")

    while is_run():
        target = chr(65 + random.randint(0, 25))
        x = random.randint(0, 620)
        for y in range(16, 460):
            set_color("white")
            draw_text(x, y, target)
            if has_kb_hit():
                key = get_char()
                if key.upper() == target:
                    fill_rect(x - 2, y - 22, x + 22, y + 2)  # clear the char and generate next char
                    break
                if key == " ":
                    show_goodbye()
                    close_graph()
                    exit()
            delay_fps(60)
            fill_rect(x - 2, y - 22, x + 22, y + 2)  # clear the char

    close_graph()

easy_run(main)
Key Pressed

We can use has_kb_msg() to see if there is any key pressed, and use get_key() to get the pressed key. has_kb_msg() is non-blocking, and get_key() is blocking.

Turtle Graphics

Turtle Graphics

The turtle graphics is a classic and popular way to introducing programming to kids.

In the turtle graphics, you control a turtle to move around the graphics window. The traces left by its move form drawings.

In the following program, we use turtle graphics to draw a star:

In the main function, we:

  1. use create_world(800,600) to create a 800x600 drawing canvas (drawing window)
  2. set the pen color to red and the fill color to red
  3. use right(90) command to turn the turtle 90 degrees clockwise.
  4. use forward(100) command to move the turtle 100 steps forward,then turn the turtle 144 degrees clockwise.
  5. repeat the above step 5 times
  6. use close_world() to close the drawing window.
from easygraphics import *
from easygraphics.turtle import *

def main():
    create_world(800,600)
    set_color("red")
    set_fill_color("red")
    right(90)
    for i in range(5):
        forward(100)
        right(144)
    pause()
    close_world()

easy_run(main)

Basic Commands

In this tutorial, we will introduce basic commands of the turtle graphics.

Move the turtle

forward(x) function move the turtle x steps forward. fd(x) is the short form of forward(x).

from easygraphics.turtle import *

def main():
    create_world(250,250)
    fd(100)
    pause()
    close_world()

easy_run(main)
_images/01_fd.png

backward(x) function move the turtle x steps backward. back(x) and bk(x) is the short form of backward(x).

from easygraphics.turtle import *

def main():
    create_world(400,400)
    bk(100)
    pause()
    close_world()

easy_run(main)
_images/01_bk.png
Turning the turtle

right_turn(x) turns the turtle x degrees clockwise. right(x) and rt(x) are its short form.

left_turn(x) turns the turtle x degrees counter-clockwise. left(x) and lt(x) are its short form

The following program draws a 30 degree angle.

from easygraphics.turtle import *

def main():
    create_world(400,400)
    fd(80)
    bk(80)
    rt(30)
    fd(80)
    pause()
    close_world()

easy_run(main)
_images/01_angle.png
Speed of the turtle

We can use set_speed() to control the turtle’s moving speed. Speed is the more the fast, and 1 is the slowest. If you don’t need the animation, use set_immediate(True) to disable it.

Pen Up and Pen Down

If you want to move the turtle without a trace, you can use pen_up and pen_down.

By default the turtle is in pen down state, which means its move will leave a trace.

If the turtle is in pen up state, its move will not leave a trace.

The following program use pen up and down to draw one square inside another.

from easygraphics.turtle import *

def main():
    create_world(400,400)

    # draw the inside rectangle
    for i in range(4):
        fd(100)
        lt(90)

    # use pen_up to move the turtle without a trace
    pen_up()
    rt(135)
    fd(70)
    lt(135)
    pen_down()

    # draw the outside rectangle
    for i in range(4):
        fd(200)
        lt(90)

    pause()
    close_world()

easy_run(main)
_images/01_pen_up.png
Show and Hide the Turtle

When the drawing is finished, we can hide() the turtle.

And show() makes the turtle visible again.

from easygraphics.turtle import *

def main():
    create_world(400,400)
    for i in range(4):
        fd(100)
        lt(90)

    hide()
    pause()
    close_world()

easy_run(main)
_images/01_hide.png

Interactive Mode

On Windows and Linux, we can run easygraphics in python’s interactive mode.

Demo fro easygraphics
from easygraphics import *
init_graph()
line(50,50,100,100)

close_graph()
Demo for Turtle Graphics
from easygraphics.turtle import *
create_world()
fd(100)
lt(90)
close_world()
Clear the screen

If you are using turtle graphics, clear_screen() clears the turtle graphics window, and reset the turtle to its initial position and state. cs() / clear() is the short form.

If you are using easygraphics, clear_device() clears the graphics window.

Coordinates of the Turtle World

In the turtle world, we use a coordinate system as the following:

  1. The origin (0,0) is at the center of the graphics window.
  2. The x axis grows from left to right.
  3. The y axis grows from bottom to top.
_images/03_cord.png
Set the turtle’s position

setxy(x,y) set the turtle’s position to point(x,y) without a trace.

gotoxy(x,y) move the turtle to point(x,y). So if the pen is down, there will be a trace.

The turtle’s heading direction will not change.

The following program demonstrated the result of gotoxy() and setxy().

from easygraphics.turtle import *

def main():
    create_world(300,300)
    gotoxy(50,-100)
    for i in range(360):
        fd(1)
        lt(1)
    pause()
    cs()

    setxy(50,-100)
    for i in range(360):
        fd(1)
        lt(1)

    pause()
    close_world()

easy_run(main)
Set the Turtle’s heading

facing(x,y) set the turtle heading to facing point(x,y).

from easygraphics.turtle import *

def main():
    create_world(300,300)

    # set the turtle's heading to top-left corner of the graphics window
    facing(-150,150)
    fd(100)

    pause()
    close_world()

easy_run(main)

set_heading(angle) set the turtle’s new orientation to angle.

Values of the angles in the turtle world are as the following:

_images/03_polar.gif
from easygraphics.turtle import *

def main():
    create_world(300,300)

    # set the turtle's heading to top-left corner of the graphics window
    set_heading(30)
    fd(100)

    pause()
    close_world()

easy_run(main)
Get turtle’s current state

get_x() return the x coordinate value of the turtle’s position.

get_y() return the y coordinate value of the turtle’s position.

get_heading() return the angle value of the turtle’s heading.

from easygraphics.turtle import *

def main():
    create_world(300,300)

    # set the turtle heading to top-left corner of the graphics window
    facing(-150,150)
    fd(100)

    draw_text(-140, -130, "(%.2f, %.2f), heading(%.2f)" % (get_x(), get_y(), get_heading()))
    pause()
    close_world()

easy_run(main)

Advanced Commands

Fill the drawings

Drawings between begin_fill() and end_fill() will be filled using the fill color. Unclosed shapes will get closed automatically.

By default the fill color is light gray. You can use easygraphics set_fill_color() to change it.

The following program draw and fill a star. Note that we use the FillRule.WINDING_FILL rule to fill the whole star.

from easygraphics.turtle import *
from easygraphics import *


def main():
    create_world(150, 150)

    setxy(20,-50)
    set_fill_rule(FillRule.WINDING_FILL)
    begin_fill()
    for i in range(5):
        fd(100)
        lt(144)
    end_fill()

    pause()
    close_world()

easy_run(main)
_images/04_fill.png
Move in arcs

move_arc(radius,angle) moves the turtle in a arc path.

The center is radius units left of the turtle. That is, if radius > 0, the center is on the left of the turtle; if radius < 0, the center is on the right of the turtle.

Angle is the value of the angle at the circle’s center. If angle > 0, the turtle moves forward around the center; if angle < 0, the turtle moves backward around the center. So:

  • if angle > 0 and radius > 0, the turtle moves forward and turns counter-clockwise;
  • if angle > 0 and raidus < 0, the turtle move forward and turns clockwise;
  • if angle <0 and radius > 0, the turtle moves backward and turns clockwise;
  • if angle <0 and radius < 0, the turtle moves backward and turns counter-clockwise.
from easygraphics.turtle import *

def main():
    create_world(400, 300)
    set_speed(10)

    lt(45)

    fd(100)
    lt(90)
    move_arc(100, 90)
    lt(90)
    fd(100)
    lt(90)

    fd(100)
    rt(90)
    move_arc(-100, 90)
    rt(90)
    fd(100)
    rt(90)

    bk(100)
    rt(90)
    move_arc(100, -90)
    rt(90)
    bk(100)
    rt(90)

    bk(100)
    lt(90)
    move_arc(-100, -90)
    lt(90)
    bk(100)
    lt(90)

    pause()

    close_world()

easy_run(main)
_images/04_move_arc.png
Move in ellipse arcs

move_ellipse(radius_left, radius_top, angle) moves the turtle in an elliptical path.

“radius_left” is the radius of the ellipse on the direction perpendicular to the turtle’s orientation, it can be postive or negtive;”radius_top” is the radius of the ellipse on the direction parallel to the turtle’s orientation, it must be postive.

The center is radius_left units left of the turtle. That is, if radius_left > 0, the center is on the left of the turtle; if radius_left < 0, the center is on the right of the turtle.

If angle > 0, the turtle moves forward around the center; if angle < 0, the turtle moves backward around the center. So:

  • if angle > 0 and radius_left > 0, the turtle moves forward and turns counter-clockwise;
  • if angle > 0 and radius_left < 0, the turtle move forward and turns clockwise;
  • if angle <0 and radius_left > 0, the turtle moves backward and turns clockwise;
  • if angle <0 and radius_left < 0, the turtle moves backward and turns counter-clockwise.
from easygraphics.turtle import *
from easygraphics import *

def main():
    create_world(400, 300)
    set_speed(5)

    lt(45)

    set_fill_color(Color.LIGHT_RED)
    begin_fill()
    fd(100)
    lt(90)
    move_ellipse(100, 50, 90)
    lt(90)
    fd(50)
    lt(90)
    end_fill()

    begin_fill()
    fd(100)
    rt(90)
    move_ellipse(-100, 50, 90)
    rt(90)
    fd(50)
    rt(90)
    end_fill()

    begin_fill()
    bk(100)
    rt(90)
    move_ellipse(100, 50, -90)
    rt(90)
    bk(50)
    rt(90)
    end_fill()

    begin_fill()
    bk(100)
    lt(90)
    move_ellipse(-100, 50, -90)
    lt(90)
    bk(50)
    lt(90)
    end_fill()

    pause()

    close_world()

easy_run(main)
_images/04_move_ellipse.png
Use easygraphics functions

Most of the easygraphics functions can be used in turtle graphics.

The following program use easygraphics functions to set the line width and colors, draw a circle, and fill a rectangle.

from easygraphics.turtle import *
from easygraphics import *

def main():
    create_world(300,300)

    set_line_width(3)
    set_color("red")
    set_background_color("lightgray")
    set_fill_color(Color.LIGHT_BLUE)

    begin_fill()
    for i in range(4):
        fd(100)
        lt(90)
    end_fill()

    circle(50,50,30)
    fill_rect(-100,-100,-50,-50)
    pause()
    close_world()

easy_run(main)
_images/04_easy_funcs.png

Dialogs

Dialogs

Easygraphics provides many predefined dialogs to communicate with user interactively.

Output Dialogs
show_html(title, text, width, height) Displays some html text in a window.
show_image_dialog(image, title) Display the image in a dialog.
show_lists_table(*args, column_names, title, …) Displays list of datas in a table
show_message(message, title) Simple message box.
show_objects(datas, fields, field_names, …) Displays list of objects in a table
show_text(title, text, width, height) Displays some text in a window.
show_table(datas, fields, field_names, …) Displays list of objects in a table
show_code(title, code, width, height) Displays some text in a window, in a monospace font.
show_file(file_name, title, file_type, …) Displays a file in a window.
Input Dialogs
get_choice(message, title, choices) Simple dialog to ask a user to select an item within a drop-down list
get_color([color]) Display a color picker and return the selected color
get_continue_or_cancel(question, title, …) Continue or cancel question, shown as a warning (i.e.
get_date(title) Calendar widget
get_directory_name(title) Gets the name (full path) of an existing directory
get_file_names(title, filter) Gets the names (full path) of existing files
get_float(message, title, default_value, …) Simple dialog to ask a user to select a floating point number within a certain range and a maximum precision.
get_int(message, title, default_value, min_, …) Simple dialog to ask a user to select an integer within a certain range.
get_list_of_choices(title, choices) Show a list of possible choices to be selected.
get_many_strings(title, labels, masks) Multiple strings input
get_new_password(title, labels) Change password input box.
get_password(message, title) Simple password input box.
get_save_file_name(title, filter) Gets the name (full path) of of a file to be saved.
get_string(message, title, default_response) Simple text input box.
get_username_password(title, labels) User name and password input box.
get_yes_or_no(question, title) Simple yes or no question.

In the following program, click the graphics window to open a color dialog, select a color and set it as the background.

from easygraphics import *
from easygraphics.dialog import *

def main():
    init_graph(600, 400)
    set_render_mode(RenderMode.RENDER_MANUAL)

    while is_run():
        if has_mouse_msg():
            x, y, type, buttons = get_mouse_msg()
            if type == MouseMessageType.PRESS_MESSAGE:
                color = get_color(get_background_color())
                set_background_color(color)
        delay_fps(60)

    close_graph()

easy_run(main)

Processing

Drawing using Processing

Processing is a simple programming environment to help user create interactive animations. easygraphics.processing is a processing-like animation framework.

In processing, we override (redefine) some key functions to tell the framework how to work.

In the following program, we redefined two functions in processing to draw a rotating star.

The function setup() is called by the framework when the program begins.

We use it to do preparing works, such as defining window size, setting foreground , background color and frame refresh rate(fps), and so on.

The function draw() is called by the framework to draw frames.

Each time before a frame is to be displayed, this function is called.

Finally we use run_app(globals()) to start the processing frame work.

from easygraphics.processing import *
from easygraphics import *

# this overriding function is called by processing at the beginning
def setup():
    set_size(800, 600)
    set_fill_color("red")

t = 0

# this overriding function is called by processing every frame
def draw():
    global t
    clear()
    t = t + 1
    t = t % 360
    translate(400, 300)
    rotate(t)
    begin_shape()
    for i in range(5):
        vertex(100, 0)
        rotate(144)
    end_shape(True)


# run the processing app
run_app(globals())

Miscs

Music(Audio)

Easygraphics provides simple ways to play musics.

The following program shows how to use the functions in easygraphics.music to play music:

from easygraphics.music import *
from easygraphics.dialog import *

# For legal reasons please prepare a music file by yourself
load_music("test.mp3")
play_music()
show_message("ok!")
close_music()

Examples

Animations

Games

Turtle Graphis

Qt Widget

Contributing

Credits

Development Lead

Contributors

History

1.0.20

  • add: Image.copy() method
  • change: draw_image() add width/height parameters ( can copy image with scale)
  • change: only create direct image buffer view when using floodfill()

1.0.19

  • add: Image.scaled() method

1.0.18

  • add: put_image()
  • change: capture_screen()’s 3rd and 4th parameter to width and height
  • add: more FillStyle consts

1.0.17

  • fix: dialogs dosen’t work in normal pyqt program
  • change: contains_control() -> contains_ctrl()
  • add: load_image() throw value error if the image file is not exist
  • fix: get_mouse_msg() / get_char() / get_key() not quit correctly when the graphics window is closed

1.0.16

  • add: set_antialiasing()
  • add: contains_control()/contains_alt()/contains_shit()/contains_meta()
  • change: get_mouse_message() now return a MouseMessage object
  • change: get_key() now return a KeyMessage object

1.0.15

  • change: use queue to store keyboard/mouse message
  • remove: set_message_outdate_duration()
  • change: now get_message() return 5 results instead of 4
  • add: clear_mouse_msg(), clear_key_msg(), clear_char_msg()
  • add: create_image_from_file()

1.0.14

  • fix: processing not working
  • fix: get_key() and has_kb_msg() not working
  • add: set_message_outdate_duration()
  • add: bezier_point and bezier_tangent functions
  • add: curve_point and curve_tanget functions
  • add more documents and examples

1.0.13.1

  • fix: immediate mode not work
  • fix: set_flip_y() dosen’t work when reused after reset_transform()

1.0.13

  • add easy_run mode
  • now the easy_run mode is the preferred mode to run easygraphics. It can work under Linux, macOS and windows.

1.0.12

  • fix: the drawing is not stopped immediately after the turtle window is closed()

1.0.11

  • fix: dialog get_username_password() hangs.
  • fix: dialog get_color() not work
  • fix: dialog show_html()/show_code()/show_text() not work

1.0.10

  • add: show_objects() now can show a DataFrame.

1.0.9

  • add: enable_sorting parameter in show_objects()

1.0.8

  • fix: crash when show_objects() called successively.
  • dialogs will close the auto-started qapplication instance when exception raised.

1.0.7

  • fix: show_objects() don’t show non-primitive-type properties correctly

1.0.6

  • change: get_open_file_name()/get_file_names()/get_save_file_name() now use native dialogs, to avoid crash on pyqt >= 5.11.3
  • add: FileFilter const class, and filter parameter in get_open_file_name()/get_file_names()/get_save_file_name()

1.0.5

  • add: get_open_file_name() to dialog package.
  • fix: get_open_file_name()/get_file_names()/get_save_file_name() not work
  • change: get_open_file_name()/get_file_names()/get_save_file_name() return filename(s), instead of tuple

1.0.4

  • remove the y-flip setting in ortho_look_at(). If you want to flip y, use set_flip_y() instead

1.0.3

  • add: ortho_look_at() function to map 3d point to 2d
  • add: isometric_projection() function to map 3d point to 2d from 45degree view port

1.0.2

  • add: press ctrl+shift+alt+F10 will create a snapshot of the graphics window.
    The snapshot is saved in the running folder.
  • change: close turtle window will automatically close the animation of turtle moving.

1.0.1

  • add: fps settings in easygraphics.processing module
  • update: translations
  • change: easygraphics.processing module now use functions in easygraphics modules to draw. (Remove duplication defines.)

1.0.0

  • fix: hangs in inactive shell when init_graph again after close_graph()

0.10.1

  • add: color_gray() function.
  • change: change lines/polylines/polygon functions parameters
  • add: curve() / draw_curve() to draw Catmull-Rom splines.
  • add: curve_vertex() to define curve vertices.
  • fix: crash when close_graph() and init_graph() again

0.10.0

  • change: reimplement close_graph(), simplifies graphics window close event processing.
  • add: add begin_shape()/vertex()/bezier_vertex()/quadratic_vertex()/end_shape() functions to easygraphics.

0.9.24

  • add begin_recording()/add_record()/save_recording()/end_recording() to create animated png files.
  • add ShapeMode consts
  • add set_ellipse_mode() and set_rect_mode() to Image class
  • add easygraphics.processing module
  • fix: Image’s save_settings()/restore_settings() now save most settings.
  • update: ellipse_mode apply to arc/chord/pie shape drawings.
  • add quadratic()/draw_quadratic() function to Image class and easygraphics.processing subpackage
  • add begin_shape()/vertex()/bezier_vertex()/quadratic_vertex()/end_shape() function to Image class and easygraphics.processing subpackage
  • change: bezier()/draw_bezier now use seperate coordinate values as paramter instead of list.
  • add VertexType consts
  • add: begin_shape() ‘s type parameter
  • add: end_shape()’s close parameter
  • fix: succesive dialog calls may crash the program
  • add: fill_image() function to Image class

0.9.23

  • fix: frame jumping because of errors in delay_jfps()

0.9.22

  • fix: turtle icon position error when translated.
  • fix: hangs when running in qtconsole and spyder

0.9.21

  • add: show_lists_table() to display data lists in table
  • add: get_transform()/set_transform()/push_transform()/pop_transform()
  • change to BSD license
  • fix: close graphics window when drawing in is_run() and delay_fps()/delay_jfps() loops not throw exception

0.9.20

  • fix: successive dialog calls may crash program.

0.9.19.2

  • fix: license description in readme

0.9.19.1

  • fix: license description in setup.py

0.9.19

  • change to MIT License

0.9.18

  • add ImageWidget and TurtleWidget classes, to embed easygraphics in Qt Applications

0.9.17

easygraphics.turtle:

  • add: is_out_of_window() to check if the turtle is out of the graphics window

0.9.16

  • redefine pause() in turtle
  • redefine is_run() in turtle
  • fix: default turtle speed
  • change: meaning of the turtle’s move_arc() function’s parameters
  • add: move_ellipse() function in easygraphics.turtle package

0.9.15

  • fix package error in setup.py
  • change turtle’s default speed to 10

0.9.14

  • add: move_arc() function to move turtle in arc

0.9.13

  • add: set_fill_rule() / get_fill_rule() function, to control how the polygons are filled.
  • add: FillRule consts
  • Finish chinese translations for apis.
  • fix: filling glitches in end_fill()

0.9.12

  • Revert 0.9.11 ‘s angle system change. Keep arc/pie/chord compatible with BGI.
  • add show_image() function, to display drawings in the jupyter qtconsole or notebook.
  • add show_image_dialog() function, to display a qimage in the dialog.

0.9.11

  • fix: now arc/pie/chord drawing functions has the same angle system with rotate()

0.9.10

  • add: easygraphics.turtle package which implements the turtle graphics.
  • change: now rotate()/skew() can transform around any point
  • change: now reflect() can using lines not passing the origin as the reflecting axis.

0.9.9

  • add set_flip_y() to make y-axis grows bottom-up. (use reflect() will make texts get reflected too.)

0.9.8.1

  • fix: legacy and music subpackage not packed in the binary distributions.

0.9.8

  • fix: delay_fps() now work properly in Manual render mode
  • finish chinese translations for tutorials

0.9.7

  • add: load_image() to load image from files
  • add: to_alpha() to make a transparently color
  • change: use Source Over as the default composition mode (the same with Qt)
  • more tutorials
  • add: show_table() to display table infomation in a dialog
  • change: rename mouse_msg() to has_mouse_msg()
  • change: rename kb_hit() to has_kb_hit()
  • change: rename get_mouse() to get_mouse_msg()
  • change: rename kb_msg() to has_kb_msg()
  • finish the tutorials.

0.9.6

  • add: reflection (mirror/flip) and shear (skew) operations.

0.9.5

  • add: headless mode support (no graphics window mode, use it to draw pictures)

0.9.4

  • add: easygraphics.legacy package to better compatible with old BGI programs.
  • add: get_click() function to get mouse click event
  • change: background implementation to make set_background_color() work correctly
  • add: now can use name (“red”), color string (“#ff0000), integer color rgb value (0xff0000)
    in set_color(), set_fill_color(), set_background_color() functions
  • add: cymk() and hsv() to get CYMK and HSV format color
  • more tutorials

0.9.3

  • fix : Readme

0.9.2

  • add: easygraphics functions can run in the interactive mode (eg. IPython) correctly
  • add: dialogs (in easygraphics.dialog package, adopted from
    easygui_qt )
  • add: create and save to/from file
  • add image transforms (translate/rotate/scale)
  • add view port support
  • add sphinx docs
  • upload docs to readthedocs.org

0.9.1

  • add readme text
  • add delay_fps() and rgb() functions

0.9.0

0.1.0

  • First release on github

Indices and tables