Graphics¶
This package assemble all low level function to draw object. The whole graphics package is compatible OpenGL ES 2.0, and have a lot of rendering optimizations.
The basics¶
For drawing on a screen, you will need :
- a Canvas object.
- Instruction objects.
Each widget in Kivy already have by default their Canvas. When you are creating a widget, you can create all the instructions needed for drawing. If self is your current widget, you can do:
from kivy.graphics import *
with self.canvas:
# Add a red color
Color(1., 0, 0)
# Add a rectangle
Rectangle(pos=(10, 10), size=(500, 500))
The instructions Color and Rectangle are automaticly added to the canvas object, and will be used when the window drawing will happen.
GL Reloading mechanism¶
New in version 1.2.0.
During the lifetime of the application, the OpenGL context might be lost. This is happening:
- When window is resized, on MacOSX and Windows platform, if you’re using pygame as window provider, cause of SDL 1.2. In the SDL 1.2 design, it need to recreate a GL context everytime the window is resized. This is fixed in SDL 1.3, but pygame is not available on it by default yet.
- when Android release the app resources: when your application goes to background, android system might reclaim your opengl context to give the resource to another app. When the user switch back to your application, a newly gl context is given to you.
Starting from 1.2.0, we introduced a mechanism for reloading all the graphics resources using the GPU: Canvas, FBO, Shader, Texture, VBO, VertexBatch:
- VBO and VertexBatch are constructed by our graphics instructions. We have all the data to reconstruct when reloading.
- Shader: same as VBO, we store the source and values used in the shader, we are able to recreate the vertex/fragment/program.
- Texture: if the texture have a source (an image file, an atlas...), the image is reloaded from the source, and reuploaded to the GPU.
You should cover theses cases yourself:
- Texture without source: if you manually created a texture, and manually blit data / buffer to it, you must handle the reloading yourself. Check the Texture to learn how to manage that case. (The text rendering is generating the texture, and handle already the reloading. You don’t need to reload text yourself.)
- FBO: if you added / removed / drawed things multiple times on the FBO, we can’t reload it. We don’t keep a history of the instruction put on it. As texture without source, Check the Framebuffer to learn how to manage that case.
- class kivy.graphics.Bezier¶
Bases: kivy.graphics.instructions.VertexInstruction
A 2d Bezier curve.
New in version 1.0.8.
Parameters : - points: list
List of points in the format (x1, y1, x2, y2...)
- segments: int, default to 180
Define how much segment is needed for drawing the ellipse. The drawing will be smoother if you have lot of segment.
- loop: bool, default to False
Set the bezier curve to join last point to first.
- dash_length: int
length of a segment (if dashed), default 1
- dash_offset: int
distance between the end of a segment and the start of the next one, default 0, changing this makes it dashed.
- dash_length¶
Property for getting/stting the length of the dashes in the curve
- dash_offset¶
Property for getting/setting the offset between the dashes in the curve
- points¶
Property for getting/settings points of the triangle
Warning
This will always reconstruct the whole graphics from the new points list. It can be very CPU expensive.
- segments¶
Property for getting/setting the number of segments of the curve
- class kivy.graphics.BindTexture¶
Bases: kivy.graphics.instructions.ContextInstruction
BindTexture Graphic instruction. The BindTexture Instruction will bind a texture and enable GL_TEXTURE_2D for subsequent drawing.
Parameters : - texture: Texture
specifies the texture to bind to the given index
- source¶
Set/get the source (filename) to load for texture.
- class kivy.graphics.BorderImage¶
Bases: kivy.graphics.vertex_instructions.Rectangle
A 2d border image. The behavior of the border image is similar to the concept of CSS3 border-image.
Parameters : - border: list
Border information in the format (top, right, bottom, left). Each value is in pixels.
- border¶
Property for getting/setting the border of the class
- class kivy.graphics.Callback¶
Bases: kivy.graphics.instructions.Instruction
New in version 1.0.4.
A Callback is an instruction that will be called when the drawing operation is performed. When adding instructions to a canvas, you can do this:
with self.canvas: Color(1, 1, 1) Rectangle(pos=self.pos, size=self.size) Callback(self.my_callback)
The definition of the callback must be:
def my_callback(self, instr): print 'I have been called!'
Warning
Note that if you perform many and/or costly calls to callbacks, you might potentially slow down the rendering performance significantly.
The drawing of your canvas can not happen until something new happens. From your callback, you can ask for an update:
with self.canvas: self.cb = Callback(self.my_callback) # then later in the code self.cb.ask_update()
If you use the Callback class to call rendering methods of another toolkit, you will have issues with the OpenGL context. The OpenGL state may have been manipulated by the other toolkit, and as soon as program flow returns to Kivy, it will just break. You can have glitches, crashes, black holes might occur, etc. To avoid that, you can activate the reset_context option. It will reset the OpenGL context state to make Kivy’s rendering correct, after the call to your callback.
Warning
The reset_context is not a full OpenGL reset. If you have issues regarding that, please contact us.
- ask_update()¶
Inform the parent canvas that we’d like it to update on the next frame. This is useful when you need to trigger a redraw due to some value having changed for example.
New in version 1.0.4.
- reset_context¶
Set this to True if you want to reset the OpenGL context for Kivy after the callback has been called.
- class kivy.graphics.Canvas¶
Bases: kivy.graphics.instructions.CanvasBase
The important Canvas class. Use this class to add graphics or context instructions that you want to be used for drawing.
Note
The Canvas supports Python’s with statement and its enter & exit semantics.
Usage of a canvas without the with statement:
self.canvas.add(Color(1., 1., 0)) self.canvas.add(Rectangle(size=(50, 50)))
Usage of a canvas with Python’s with statement:
with self.canvas: Color(1., 1., 0) Rectangle(size=(50, 50))
- after¶
Property for getting the ‘after’ group.
- ask_update()¶
Inform the canvas that we’d like it to update on the next frame. This is useful when you need to trigger a redraw due to some value having changed for example.
- before¶
Property for getting the ‘before’ group.
- draw()¶
Apply the instruction on our window.
- class kivy.graphics.Color¶
Bases: kivy.graphics.instructions.ContextInstruction
Instruction to set the color state for any vertices being drawn after it. All the values passed are between 0 and 1, not 0 and 255.
In Python, you can do:
from kivy.graphics import Color # create red color c = Color(1, 0, 0) # create blue color c = Color(0, 1, 0) # create blue color with 50% alpha c = Color(0, 1, 0, .5) # using hsv mode c = Color(0, 1, 1, mode='hsv') # using hsv mode + alpha c = Color(0, 1, 1, .2, mode='hsv')
In kv lang:
<Rule>: canvas: # red color Color: rgb: 1, 0, 0 # blue color Color: rgb: 0, 1, 0 # blue color with 50% alpha Color: rgba: 0, 1, 0, .5 # using hsv mode Color: hsv: 0, 1, 1 # using hsv mode + alpha Color: hsv: 0, 1, 1 a: .5
- a¶
Alpha component, between 0-1
- b¶
Blue component, between 0-1
- g¶
Green component, between 0-1
- h¶
Hue component, between 0-1
- hsv¶
HSV color, list of 3 values in 0-1 range, alpha will be 1.
- r¶
Red component, between 0-1
- rgb¶
RGB color, list of 3 values in 0-1 range, alpha will be 1.
- rgba¶
RGBA color, list of 4 values in 0-1 range
- s¶
Saturation component, between 0-1
- v¶
Value component, between 0-1
- class kivy.graphics.ContextInstruction¶
Bases: kivy.graphics.instructions.Instruction
The ContextInstruction class is the base for the creation of instructions that don’t have a direct visual representation, but instead modify the current Canvas’ state, e.g. texture binding, setting color parameters, matrix manipulation and so on.
- class kivy.graphics.Ellipse¶
Bases: kivy.graphics.vertex_instructions.Rectangle
A 2D ellipse.
New in version 1.0.7: added angle_start + angle_end
Parameters : - segments: int, default to 180
Define how much segment is needed for drawing the ellipse. The drawing will be smoother if you have lot of segment.
- angle_start: int default to 0
Specifies the starting angle, in degrees, of the disk portion
- angle_end: int default to 360
Specifies the ending angle, in degrees, of the disk portion
- angle_end¶
Angle end of the ellipse in degrees, default to 360
- angle_start¶
Angle start of the ellipse in degrees, default to 0
- segments¶
Property for getting/setting the number of segments of the ellipse
- class kivy.graphics.Fbo¶
Bases: kivy.graphics.instructions.RenderContext
Fbo class for wrapping the OpenGL Framebuffer extension. The Fbo support “with” statement.
Parameters : - clear_color: tuple, default to (0, 0, 0, 0)
Define the default color for clearing the framebuffer
- size: tuple, default to (1024, 1024)
Default size of the framebuffer
- push_viewport: bool, default to True
If True, the OpenGL viewport will be set to the framebuffer size, and will be automatically restored when the framebuffer released.
- with_depthbuffer: bool, default to False
If True, the framebuffer will be allocated with a Z buffer.
- texture: Texture, default to None
If None, a default texture will be created.
- add_reload_observer()¶
Add a callback to be called after the whole graphics context have been reloaded. This is where you can reupload your custom data in GPU.
New in version 1.2.0.
Parameters : - callback: func(context) -> return None
The first parameter will be the context itself
- bind()¶
Bind the FBO to the current opengl context. Bind mean that you enable the Framebuffer, and all the drawing operations will act inside the Framebuffer, until release() is called.
The bind/release operation are automatically done when you add graphics object in it. But if you want to manipulate a Framebuffer yourself, you can use it like this:
self.fbo = FBO() self.fbo.bind() # do any drawing command self.fbo.release() # then, your fbo texture is available at print self.fbo.texture
- clear_buffer()¶
Clear the framebuffer with the clear_color.
You need to bound the framebuffer yourself before calling this method:
fbo.bind() fbo.clear_buffer() fbo.release()
- clear_color¶
Clear color in (red, green, blue, alpha) format.
- release()¶
Release the Framebuffer (unbind).
- remove_reload_observer()¶
Remove a callback from the observer list, previously added by add_reload_observer().
New in version 1.2.0.
- size¶
Size of the framebuffer, in (width, height) format.
If you change the size, the framebuffer content will be lost.
- texture¶
Return the framebuffer texture
- class kivy.graphics.GraphicException¶
Bases: exceptions.Exception
Exception fired when a graphic error is fired.
- class kivy.graphics.Instruction¶
Bases: object
Represents the smallest instruction available. This class is for internal usage only, don’t use it directly.
- class kivy.graphics.InstructionGroup¶
Bases: kivy.graphics.instructions.Instruction
Group of Instruction. Adds the possibility of adding and removing graphics instruction.
- add()¶
Add a new Instruction to our list.
- clear()¶
Remove all the Instruction.
- get_group()¶
Return an iterable with all the Instruction with a specific group name.
- insert()¶
Insert a new Instruction in our list at index.
- remove()¶
Remove an existing Instruction from our list.
- remove_group()¶
Remove all Instruction with a specific group name.
- class kivy.graphics.Line¶
Bases: kivy.graphics.instructions.VertexInstruction
A 2d line.
New in version 1.0.8: dash_offset and dash_length have been added
Parameters : - points: list
List of points in the format (x1, y1, x2, y2...)
- dash_length: int
length of a segment (if dashed), default 1
- dash_offset: int
offset between the end of a segments and the begining of the next one, default 0, changing this makes it dashed.
- dash_length¶
Property for getting/setting the length of the dashes in the curve
New in version 1.0.8.
- dash_offset¶
Property for getting/setting the offset between the dashes in the curve
New in version 1.0.8.
- points¶
Property for getting/settings points of the line
Warning
This will always reconstruct the whole graphics from the new points list. It can be very CPU expensive.
- class kivy.graphics.MatrixInstruction¶
Bases: kivy.graphics.instructions.ContextInstruction
Base class for Matrix Instruction on canvas
- matrix¶
Matrix property. Numpy matrix from transformation module setting the matrix using this porperty when a change is made is important, becasue it will notify the context about the update
- class kivy.graphics.Mesh¶
Bases: kivy.graphics.instructions.VertexInstruction
A 2d mesh.
The format of vertices are actually fixed, this might change in a future release. Right now, each vertex is described with 2D coordinates (x, y) and a 2D texture coordinate (u, v).
In OpenGL ES 2.0 and in our graphics implementation, you cannot have more than 65535 indices.
A list of vertices is described as:
vertices = [x1, y1, u1, v1, x2, y2, u2, v2, ...] | | | | +---- i1 ----+ +---- i2 ----+
If you want to draw a triangles, put 3 vertices, then you can make an indices list as:
indices = [0, 1, 2]New in version 1.1.0.
Parameters : - vertices: list
List of vertices in the format (x1, y1, u1, v1, x2, y2, u2, v2...)
- indices: list
List of indices in the format (i1, i2, i3...)
- mode: str
Mode of the vbo. Check mode for more information. Default to ‘points’.
- indices¶
Vertex indices used to know which order you wanna do for drawing the mesh.
- mode¶
VBO Mode used for drawing vertices/indices. Can be one of: ‘points’, ‘line_strip’, ‘line_loop’, ‘lines’, ‘triangle_strip’, ‘triangle_fan’
- vertices¶
List of x, y, u, v, ... used to construct the Mesh. Right now, the Mesh instruction doesn’t allow you to change the format of the vertices, mean it’s only x/y + one texture coordinate.
- class kivy.graphics.Point¶
Bases: kivy.graphics.instructions.VertexInstruction
A 2d line.
Parameters : - points: list
List of points in the format (x1, y1, x2, y2...)
- pointsize: float, default to 1.
Size of the point (1. mean the real size will be 2)
Warning
Starting from version 1.0.7, vertex instruction have a limit of 65535 vertices (indices of vertex to be accurate). 2 entry in the list (x + y) will be converted to 4 vertices. So the limit inside Point() class is 2^15-2.
- add_point()¶
Add a point into the current points list.
If you intend to add multiple point, prefer to use this method, instead of reassign a new points list. Assigning a new points list will recalculate and reupload the whole buffer into GPU. If you use add_point, it will only upload the changes.
- points¶
Property for getting/settings points of the triangle
- pointsize¶
Property for getting/setting point size
- class kivy.graphics.PopMatrix¶
Bases: kivy.graphics.instructions.ContextInstruction
Pop Matrix from context’s matrix stack onto model view
- class kivy.graphics.PushMatrix¶
Bases: kivy.graphics.instructions.ContextInstruction
PushMatrix on context’s matrix stack
- class kivy.graphics.Quad¶
Bases: kivy.graphics.instructions.VertexInstruction
A 2d quad.
Parameters : - points: list
List of point in the format (x1, y1, x2, y2, x3, y3, x4, y4)
- points¶
Property for getting/settings points of the quads
- class kivy.graphics.Rectangle¶
Bases: kivy.graphics.instructions.VertexInstruction
A 2d rectangle.
Parameters : - pos: list
Position of the rectangle, in the format (x, y)
- size: list
Size of the rectangle, in the format (width, height)
- pos¶
Property for getting/settings the position of the rectangle
- size¶
Property for getting/settings the size of the rectangle
- class kivy.graphics.RenderContext¶
Bases: kivy.graphics.instructions.Canvas
The render context stores all the necessary information for drawing, i.e.:
- The vertex shader
- The fragment shader
- The default texture
- The state stack (color, texture, matrix...)
- class kivy.graphics.Rotate¶
Bases: kivy.graphics.context_instructions.Transform
Rotate the coordinate space by applying a rotation transformation on the modelview matrix. You can set the properties of the instructions afterwards with e.g.:
rot.angle = 90 rot.axis = (0,0,1)
- angle¶
Property for getting/settings the angle of the rotation
- axis¶
Property for getting/settings the axis of the rotation
The format of the axis is (x, y, z).
- set()¶
Set the angle and axis of rotation
>>> rotationobject.set(90, 0, 0, 1)
- class kivy.graphics.Scale¶
Bases: kivy.graphics.context_instructions.Transform
Instruction to perform a uniform scale transformation
- scale¶
Property for getting/setting the scale.
The same scale value is applied on all axis.
- class kivy.graphics.StencilPop¶
Bases: kivy.graphics.instructions.Instruction
Pop the stencil stack. See module documentation for more information.
- class kivy.graphics.StencilPush¶
Bases: kivy.graphics.instructions.Instruction
Push the stencil stack. See module documentation for more information.
- class kivy.graphics.StencilUse¶
Bases: kivy.graphics.instructions.Instruction
Use current stencil buffer as a mask. Check module documentation for more information.
- class kivy.graphics.StencilUnUse¶
Bases: kivy.graphics.instructions.Instruction
Use current stencil buffer to unset the mask.
- class kivy.graphics.Translate¶
Bases: kivy.graphics.context_instructions.Transform
Instruction to create a translation of the model view coordinate space
- x¶
Property for getting/setting the translation on X axis
- xy¶
2 tuple with translation vector in 2D for x and y axis
- xyz¶
3 tuple translation vector in 3D in x, y, and z axis
- y¶
Property for getting/setting the translation on Y axis
- z¶
Property for getting/setting the translation on Z axis
- class kivy.graphics.Triangle¶
Bases: kivy.graphics.instructions.VertexInstruction
A 2d triangle.
Parameters : - points: list
List of point in the format (x1, y1, x2, y2, x3, y3)
- points¶
Property for getting/settings points of the triangle
- class kivy.graphics.VertexInstruction¶
Bases: kivy.graphics.instructions.Instruction
The VertexInstruction class is the base for all graphics instructions that have a direct visual representation on the canvas, such as Rectangles, Triangles, Lines, Ellipse and so on.
- source¶
This property represents the filename to load the texture from. If you want to use an image as source, do it like this:
with self.canvas: Rectangle(source='mylogo.png', pos=self.pos, size=self.size)
Here’s the equivalent in Kivy language:
<MyWidget>: canvas: Rectangle: source: 'myfilename.png' pos: self.pos size: self.size
Note
The filename will be searched with the kivy.resources.resource_find() function.
- tex_coords¶
This property represents the texture coordinates used for drawing the vertex instruction. The value must be a list of 8 values.
A texture coordinate has a position (u, v), and a size (w, h). The size can be negative, and would represent the ‘flipped’ texture. By default, the tex_coords are:
[u, v, u + w, v, u + w, y + h, u, y + h]
You can pass your own texture coordinates, if you want to achieve fancy effects.
Warning
The default value as mentioned before can be negative. Depending on the image and label providers, the coordinates are flipped vertically, because of the order in which the image is internally stored. Instead of flipping the image data, we are just flipping the texture coordinates to be faster.
- texture¶
Property that represents the texture used for drawing this Instruction. You can set a new texture like this:
from kivy.core.image import Image texture = Image('logo.png').texture with self.canvas: Rectangle(texture=texture, pos=self.pos, size=self.size)
Usually, you will use the source attribute instead of the texture.
- class kivy.graphics.ClearColor¶
Bases: kivy.graphics.instructions.Instruction
ClearColor Graphic Instruction.
New in version 1.3.0.
Sets the clear color used to clear buffers with glClear function, or ClearBuffers graphics instructions.
- a¶
Alpha component, between 0-1
- b¶
Blue component, between 0-1
- g¶
Green component, between 0-1
- r¶
Red component, between 0-1
- rgb¶
RGB color, list of 3 values in 0-1 range, alpha will be 1.
- rgba¶
RGBA used for clear color, list of 4 values in 0-1 range
- class kivy.graphics.ClearBuffers¶
Bases: kivy.graphics.instructions.Instruction
Clearbuffer Graphic Instruction
New in version 1.3.0.
Clear the buffers specified by the instructions buffer mask property. By default, only the coloc buffer is cleared.
- clear_color¶
If true, the color buffer will be cleared
- clear_depth¶
If true, the depth buffer will be cleared
- clear_stencil¶
If true, the stencil buffer will be cleared