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()
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.
Returns flat list of the sprite tree for simplified iteration
Returns flat list of just the visible sprites - avoid children whos parents are not displayed
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 of the scene. Use either a string with hex color or an RGB triplet.
Remove all sprites from scene
instance of Colors class for color parsing
Miminum distance in pixels for a drag to occur
read only info about current framerate (frames per second)
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.
Returns the topmost visible interactive sprite for given coordinates
Scene height. Will be None until first expose (that is until first on-enter-frame signal below).
Should the stage maintain aspect ratio upon scale if Scene.scale is enabled. Defaults to true.
Mouse cursor appearance. Replace with your own cursor or set to False to have no cursor. None will revert back the default behavior
Last known x position of the mouse (set on expose event)
Last known y position of the mouse (set on expose event)
Queue redraw. The redraw will be performed not more often than the framerate allows
When specified, upon window resize the content will be scaled relative to original window size. Defaults to False.
list of sprites in scene. use add_child() to add sprites
instance of pytweener.Tweener that is used by animate() function, but can be also accessed directly for advanced control.
Scene width. Will be None until first expose (that is until first on-enter-frame signal below).
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
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 sprite. Child will be nested within parent
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).
Whether the sprite should be cached as a bitmap. Default: true Generally good when you have many static sprites
check if the given coordinates are inside the sprite’s fill or stroke path
x position of the cursor within mouse upon drag. change this value in on-drag-start to adjust drag point
y position of the cursor within mouse upon drag. change this value in on-drag-start to adjust drag point
boolean marking if sprite can be automatically dragged
Converts x, y given in the scene coordinates to sprite’s local ones coordinates
return sprite’s current transformation matrix
returns class:Scene the sprite belongs to
instance of hamster.graphics for this sprite
boolean denoting whether the sprite responds to mouse events
mouse-over cursor of the sprite. See Scene.mouse_cursor() for possible values
sprite opacity
relative x coordinate of the sprites’ rotation point
relative y coordinates of the sprites’ rotation point
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 of the sprite in radians (use math.degrees() to convert to degrees if necessary)
scale X
scale Y
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.
list of children sprites. Use add_child() to add sprites
Converts x, y from sprite’s local coordinates to scene coordinates
boolean visibility flag
drawing order between siblings. The one with the highest z_order will be on top.
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.
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.
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.
draw arc going counter-clockwise from start_angle to end_angle
draw arc going clockwise from start_angle to end_angle
draw circle
clear all instructions
utility function to create layout with the default font. Size and alignment parameters are shortcuts to according functions of the pango.Layout
draw a curve. (x2, y2) is the middle point of the curve
draw ‘perfect’ ellipse, opposed to squashed circle. works also for equilateral polygons
fill rectangular area with specified color
fill and stroke the drawn area in one go
draw a rectangle. if corner_radius is specified, will draw rounded corners
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.
change width and dash of a line
display text with system’s default font
display text. font_desc is string of pango font description often handier than calling this function directly, is to create a class:Label object
this function is most likely to change
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.
Displays image by path. Currently supports only PNG images.
path to the image
A few shapes to speed up your drawing. They are full fledged Sprites.
fill color
circle height
stroke line width
stroke color
circle width
corner radius. Set bigger than 0 for rounded corners
fill color
height
stroke line width
stroke color
width
fill color
stroke line width
list of (x,y) tuples that the line should go through. Polygon will automatically close path.
stroke color
alignment. one of pango.[ALIGN_LEFT, ALIGN_RIGHT, ALIGN_CENTER]
color of label either as hex string or an (r,g,b) tuple
Ellipsize mode. Can be set to pango. [ELLIPSIZE_NONE, ELLIPSIZE_START, ELLIPSIZE_MIDDLE, ELLIPSIZE_END]
pango.FontDescription, default is the system’s font
maximum width of the label in pixels. if specified, the label will be wrapped or ellipsized depending on the wrap and ellpisize settings
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)
color for text outline (currently works only with a custom font face)
text outline thickness (currently works only with a custom font face)
font size
label text
wrapping method. Can be set to pango. [WRAP_WORD, WRAP_CHAR, WRAP_WORD_CHAR]
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.
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.
jump the the last frame of all tweens
Get a list of all tweens acting on the specified object Useful for manipulating tweens on the fly
Stop tweening an object, without completing the motion or firing the on_complete
“remove given tween without completing the motion or firing the on_complete
update tweeners. delta_seconds is time in seconds since last frame
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)