hamster.graphics

The hamster graphics library is a sprite-styled abstraction layer on top of pygtk and cairo. Create a Scene and add it to the window. Then you can start adding and manipulating sprites.

Hello world:

import gtk
from lib import graphics

class Scene(graphics.Scene):
    def __init__(self):
        graphics.Scene.__init__(self)
        label = graphics.Label("Hello World", 24, "#000", x = 5, y = 5)
        self.add_child(label) # remember to add sprites to the scene

window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.add(Scene())
window.show_all()
gtk.main()

The Scene

class graphics.Scene(interactive=True, framerate=60, background_color=None, scale=False, keep_aspect=True)

Drawing area for displaying sprites. Add sprites to the Scene by calling add_child(). Scene is descendant of gtk.DrawingArea and thus inherits all it’s methods and everything.

add_child(*sprites)

Add one or several Sprite objects to the scene

all_sprites(sprites=None)

Returns flat list of the sprite tree for simplified iteration

all_visible_sprites(sprites=None)

Returns flat list of just the visible sprites - avoid children whos parents are not displayed

animate(sprite, duration=None, easing=None, on_complete=None, on_update=None, **kwargs)

Interpolate attributes of the given object using the internal tweener and redrawing scene after every tweener update. Specify the sprite and sprite’s attributes that need changing. duration defaults to 0.4 seconds and easing to cubic in-out (for others see pytweener.Easing class).

Redraw is requested right after creating the animation. Example:

# tween some_sprite to coordinates (50,100) using default duration and easing
scene.animate(some_sprite, x = 50, y = 100)
background_color

Background color of the scene. Use either a string with hex color or an RGB triplet.

clear()

Remove all sprites from scene

colors

instance of Colors class for color parsing

drag_distance

Miminum distance in pixels for a drag to occur

fps

read only info about current framerate (frames per second)

framerate

framerate of animation. This will limit how often call for redraw will be performed (that is - not more often than the framerate). It will also influence the smoothness of tweeners.

get_sprite_at_position(x, y)

Returns the topmost visible interactive sprite for given coordinates

height

Scene height. Will be None until first expose (that is until first on-enter-frame signal below).

keep_aspect

Should the stage maintain aspect ratio upon scale if Scene.scale is enabled. Defaults to true.

mouse_cursor

Mouse cursor appearance. Replace with your own cursor or set to False to have no cursor. None will revert back the default behavior

mouse_x

Last known x position of the mouse (set on expose event)

mouse_y

Last known y position of the mouse (set on expose event)

redraw()

Queue redraw. The redraw will be performed not more often than the framerate allows

remove_child(*sprites)

Remove one or several Sprite sprites from scene

scale

When specified, upon window resize the content will be scaled relative to original window size. Defaults to False.

sprites

list of sprites in scene. use add_child() to add sprites

tweener

instance of pytweener.Tweener that is used by animate() function, but can be also accessed directly for advanced control.

width

Scene width. Will be None until first expose (that is until first on-enter-frame signal below).

Scene signals

Subscribe to signals using the connect(signal, callback) function of scene.

on-enter-frame (context) - fired before drawing sprites and will pass context to the listener

on-finish-frame (context) - fired after sprites have been drawn

on-click (button_press_event, target_sprite)

on-drag-start (motion_notify_event, drag_sprite)

on-drag (motion_notify_event, drag_sprite) - fired on each drag motion

on-drag-finish (motion_notify_event, drag_sprite)

on-mouse-move (motion_notify_event)

on-mouse-down (button_press_event) - fired when a mouse button is pressed down.

on-mouse-up (button_press_event) - fired when a mouse button is released

on-mouse-over (target_sprite) - fired when mouse cursor moves over an interactive sprite.

on-mouse-out (target_sprite) - fired when mouse cursor leaves an interactive sprite.

on-scroll (scroll_event) - fired on scroll wheel motion

Sprite objects

class graphics.Sprite(x=0, y=0, opacity=1, visible=True, rotation=0, pivot_x=0, pivot_y=0, scale_x=1, scale_y=1, interactive=False, draggable=False, z_order=0, mouse_cursor=None, cache_as_bitmap=False, snap_to_pixel=True)

The Sprite class is a basic display list building block: a display list node that can display graphics and can also contain children. Once you have created the sprite, use Scene’s add_child to add it to scene

add_child(*sprites)

Add child sprite. Child will be nested within parent

animate(duration=None, easing=None, on_complete=None, on_update=None, **kwargs)

Request paretn Scene to Interpolate attributes using the internal tweener. Specify sprite’s attributes that need changing. duration defaults to 0.4 seconds and easing to cubic in-out (for others see pytweener.Easing class).

Example::
# tween some_sprite to coordinates (50,100) using default duration and easing self.animate(x = 50, y = 100)
cache_as_bitmap

Whether the sprite should be cached as a bitmap. Default: true Generally good when you have many static sprites

check_hit(x, y)

check if the given coordinates are inside the sprite’s fill or stroke path

drag_x

x position of the cursor within mouse upon drag. change this value in on-drag-start to adjust drag point

drag_y

y position of the cursor within mouse upon drag. change this value in on-drag-start to adjust drag point

draggable

boolean marking if sprite can be automatically dragged

from_scene_coords(x=0, y=0)

Converts x, y given in the scene coordinates to sprite’s local ones coordinates

get_matrix()

return sprite’s current transformation matrix

get_scene()

returns class:Scene the sprite belongs to

graphics

instance of hamster.graphics for this sprite

interactive

boolean denoting whether the sprite responds to mouse events

mouse_cursor

mouse-over cursor of the sprite. See Scene.mouse_cursor() for possible values

opacity

sprite opacity

parent

pointer to parent Sprite or Scene

pivot_x

relative x coordinate of the sprites’ rotation point

pivot_y

relative y coordinates of the sprites’ rotation point

redraw()

queue redraw of the sprite. this function is called automatically whenever a sprite attribute changes. sprite changes that happen during scene redraw are ignored in order to avoid echoes. Call scene.redraw() explicitly if you need to redraw in these cases.

rotation

rotation of the sprite in radians (use math.degrees() to convert to degrees if necessary)

scale_x

scale X

scale_y

scale Y

snap_to_pixel

Should the sprite coordinates always rounded to full pixel. Default: true Mostly this is good for performance but in some cases that can lead to rounding errors in positioning.

sprites

list of children sprites. Use add_child() to add sprites

to_scene_coords(x=0, y=0)

Converts x, y from sprite’s local coordinates to scene coordinates

visible

boolean visibility flag

z_order

drawing order between siblings. The one with the highest z_order will be on top.

Sprite signals

Subscribe to signals using the connect(signal, callback) function of sprite.

on-mouse-over() - fired when cursor moves over the sprite.

on-mouse-out() - fired when cursor leaves the sprite.

on-click (button_press_event)

on-drag-start (motion_notify_event)

on-drag (motion_notify_event) - fired on every drag motion

on-drag-finish (motion_notify_event)

on-render () fired before rendering the sprite in case if any of the class attributes have changed (except for transformations as those are handled by matrixes, not sprite graphics). Example:

class Ball(graphics.Sprite):
    def __init__(self, color):
        graphics.Sprite.__init__(self)
        self.color = color
        self.connect("on-render", self.on_render)

    def on_render(self, sprite):
        self.graphics.clear() # clear any previous state
        self.graphics.circle(0, 0, 10)
        self.graphics.fill(self.color) # fill with the whatever color we have at the moment

Normally if you would change the color attribute of the Ball class nothing would happen as the sprite draws whatever there currently is in the instructions. But as the on_render will be called whenever a class attribute changes, this will trigger a redraw, and so the ball sprite will correctly render with the new color.

Graphics class

Scene and Sprite objects have a graphics attribute that is an instance of Graphics class. All the drawing is performed by calling functions of this class. By passing in Cairo context into constructor the Graphics class can also be used on it’s own.

class graphics.Graphics(context=None)

If context is given upon contruction, will perform drawing operations on context instantly. Otherwise queues up the drawing instructions and performs them in passed-in order when _draw is called with context.

Most of instructions are mapped to cairo functions by the same name. Where there are differences, documenation is provided.

See http://cairographics.org/documentation/pycairo/2/reference/context.html for detailed description of the cairo drawing functions.

arc(x, y, radius, start_angle, end_angle)

draw arc going counter-clockwise from start_angle to end_angle

arc_negative(x, y, radius, start_angle, end_angle)

draw arc going clockwise from start_angle to end_angle

circle(x, y, radius)

draw circle

clear()

clear all instructions

clip()
close_path()
create_layout(size=None)

utility function to create layout with the default font. Size and alignment parameters are shortcuts to according functions of the pango.Layout

curve_to(x, y, x2, y2, x3, y3)

draw a curve. (x2, y2) is the middle point of the curve

ellipse(x, y, width, height, edges=None)

draw ‘perfect’ ellipse, opposed to squashed circle. works also for equilateral polygons

fill(color=None, alpha=1)
fill_area(x, y, width, height, color, opacity=1)

fill rectangular area with specified color

fill_preserve(color=None, alpha=1)
fill_stroke(fill=None, stroke=None, line_width=None)

fill and stroke the drawn area in one go

line_to(x, y=None)
mask(pattern)
move_to(x, y)
new_path()
paint()
rectangle(x, y, width, height, corner_radius=0)

draw a rectangle. if corner_radius is specified, will draw rounded corners

rel_line_to(x, y=None)
restore_context()
rotate(radians)
save_context()
set_color(color, alpha=1)

set active color. You can use hex colors like “#aaa”, or you can use normalized RGB tripplets (where every value is in range 0..1), or you can do the same thing in range 0..65535. also consider skipping this operation and specify the color on stroke and fill.

set_font_face(face)
set_font_size(size)
set_line_style(width=None, dash=None, dash_offset=0)

change width and dash of a line

set_source(image, x=0, y=0)
set_source_pixbuf(pixbuf, x=0, y=0)
set_source_surface(surface, x=0, y=0)
show_label(text, size=None, color=None)

display text with system’s default font

show_layout(text, font_desc, alignment=<enum PANGO_ALIGN_LEFT of type PangoAlignment>, width=-1, wrap=None, ellipsize=None)

display text. font_desc is string of pango font description often handier than calling this function directly, is to create a class:Label object

show_text(text)
stroke(color=None, alpha=1)
stroke_preserve(color=None, alpha=1)
text_path(text)

this function is most likely to change

translate(x, y)

Sprites: Icons and images

Load icons and images as Sprite objects.

Image and Icon both are subclasses of BitmapSprite which performs data caching in a surface similar to target. That basically makes sure that redraws are low on CPU and conversion between source and destination is performed just once. They are fully fledges sprites, so all the interaction and transformation bits are there.

class graphics.Image(path, **kwargs)

Displays image by path. Currently supports only PNG images.

path

path to the image

class graphics.Icon(name, size=24, **kwargs)

Displays icon by name and size in the theme

name

icon name from theme

size

icon size in pixels

class graphics.BitmapSprite(image_data=None, **kwargs)

Caches given image data in a surface similar to targets, which ensures that drawing it will be quick and low on CPU. Image data can be either cairo.ImageSurface or gtk.gdk.Pixbuf

image_data

image data

Sprites: Primitives

A few shapes to speed up your drawing. They are full fledged Sprites.

class graphics.Circle(width, height, fill=None, stroke=None, line_width=1, **kwargs)
fill

fill color

height

circle height

line_width

stroke line width

stroke

stroke color

width

circle width

class graphics.Rectangle(w, h, corner_radius=0, fill=None, stroke=None, line_width=1, **kwargs)
corner_radius

corner radius. Set bigger than 0 for rounded corners

fill

fill color

height

height

line_width

stroke line width

stroke

stroke color

width

width

class graphics.Polygon(points, fill=None, stroke=None, line_width=1, **kwargs)
fill

fill color

line_width

stroke line width

points

list of (x,y) tuples that the line should go through. Polygon will automatically close path.

stroke

stroke color

class graphics.Label(text='', size=10, color=None, alignment=<enum PANGO_ALIGN_LEFT of type PangoAlignment>, font_face=None, max_width=None, wrap=None, ellipsize=None, outline_color=None, outline_width=5, **kwargs)
alignment

alignment. one of pango.[ALIGN_LEFT, ALIGN_RIGHT, ALIGN_CENTER]

color

color of label either as hex string or an (r,g,b) tuple

ellipsize

Ellipsize mode. Can be set to pango. [ELLIPSIZE_NONE, ELLIPSIZE_START, ELLIPSIZE_MIDDLE, ELLIPSIZE_END]

font_desc

pango.FontDescription, default is the system’s font

font_face

label’s FontFace

max_width

maximum width of the label in pixels. if specified, the label will be wrapped or ellipsized depending on the wrap and ellpisize settings

measure(text)

measures given text with label’s font and size. returns width, height and ascent. Ascent’s null in case if the label does not have font face specified (and is thusly using pango)

outline_color

color for text outline (currently works only with a custom font face)

outline_width

text outline thickness (currently works only with a custom font face)

size

font size

text

label text

wrap

wrapping method. Can be set to pango. [WRAP_WORD, WRAP_CHAR, WRAP_WORD_CHAR]

The Tweener

You can use the tweener on it’s own but must convenient is to use the animate() function of Scene, or alternatively the Scene.tweener that is an instance of this class.

class pytweener.Tweener(default_duration=None, tween=None)
add_tween(obj, duration=None, easing=None, on_complete=None, on_update=None, **kwargs)

Add tween for the object to go from current values to set ones. Example: add_tween(sprite, x = 500, y = 200, duration = 0.4) This will move the sprite to coordinates (500, 200) in 0.4 seconds. For parameter “easing” you can use one of the pytweener.Easing functions, or specify your own. The tweener can handle numbers, dates and color strings in hex (“#ffffff”). This function performs overwrite style conflict solving - in case if a previous tween operates on same attributes, the attributes in question are removed from that tween.

finish()

jump the the last frame of all tweens

get_tweens(obj)

Get a list of all tweens acting on the specified object Useful for manipulating tweens on the fly

kill_tweens(obj=None)

Stop tweening an object, without completing the motion or firing the on_complete

remove_tween(tween)

“remove given tween without completing the motion or firing the on_complete

update(delta_seconds)

update tweeners. delta_seconds is time in seconds since last frame

class pytweener.Tween(obj, duration, easing, on_complete, on_update, **kwargs)
class pytweener.Easing

Class containing easing classes to use together with the tweener. All of the classes have ease_in(), ease_out() and ease_in_out() functions.

Subclasses are: Back, Bounce, Circ, Cubic, Elastic, Expo, Linear, Quad, Quart, Quint, Sine, Strong

Example of tweener usage:

from pytweener import Easing

scene.animate(my_object, x = 100, easing=Easing.Cubic.ease_out)

Table Of Contents

This Page