Reader small image

You're reading from  Kivy - Interactive Applications and Games in Python

Product typeBook
Published inJun 2015
Reading LevelBeginner
Publisher
ISBN-139781785286926
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Roberto Ulloa
Roberto Ulloa
author image
Roberto Ulloa

Roberto Ulloa has a diverse academic record in multiple disciplines within the field of computer science. Currently, he is working with artificial societies as part of his PhD thesis at the University of Western Ontario. He obtained an MSc degree from the University of Costa Rica and taught programming and computer networking there. He has earned a living as a web developer, working with Python/Django and PHP/Wordpress. He collaborates with various researchers while also working on his own projects, including his blog (http://robertour.com). He constantly worries that the Internet has already become aware of itself and that we are not able to communicate with it because of the improbability of it being able to speak any of the 6,000-plus odd human languages that exist on the planet.
Read more about Roberto Ulloa

Right arrow

Chapter 2. Graphics – the Canvas

Any Kivy Widget contains a Canvas object. A Kivy Canvas is a set of drawing instructions that define the graphical representation of Widget.

Tip

Be careful with the name because it tends to be confusing! A Canvas object is not what we draw on (for example, as it is in HTML5); it is a set of instructions to draw in the coordinate space.

The coordinate space refers to the place in which we draw. All the Kivy widgets share the same coordinate space, and a Canvas instance, the instructions to draw on it. A coordinate space is not restricted to the size of the window or the application screen, which means that we can draw outside of the visible area.

We will discuss how to draw and manipulate the representation of the widgets through the instructions we add to the Canvas object. Here is a list of the most important skills that we will cover:

  • Drawing basic geometric shapes (straight and curve lines, ellipses, and polygons) through vertex instructions

  • Using colors, and...

Understanding the canvas


Before studying the examples of this chapter, it is important to recapitulate the following particularities related to the graphics display:

  • The coordinate space refers to the place in which we draw, which is not restricted to the windows size

  • A Canvas object is a set of instructions to draw in the coordinate space, not the place we draw in

  • All Widget objects contain their own Canvas (canvases, which we will see later) but all of them share the same coordinate space, the one in the App object.

For example, if we add a rotation instruction to a specific Canvas instance (for example, the canvas of a button), then this will also affect all the subsequent graphics instructions that are going to display graphics in the coordinate space. It doesn't matter if the graphics belong to canvases of different widgets; they all share the same coordinate space.

Therefore, we need to learn techniques to leave the coordinate space context in its original state after modifying it with...

Drawing basic shapes


Before starting, let's introduce the Python code that we will reuse in all the examples of this chapter:

1. # File name: drawing.py
2. from kivy.app import App
3. from kivy.uix.relativelayout import RelativeLayout
4. 
5. class DrawingSpace(RelativeLayout):
6.     pass
7. 
8. class DrawingApp(App):
9.     def build(self):
10.         return DrawingSpace()
11. 
12. if __name__=="__main__":
13.     DrawingApp().run()

We created the subclass DrawingSpace from RelativeLayout. It could have been inherited from any Widget but using RelativeLayout is generally a good choice for graphics because we usually want to draw inside the widget, and that means relative to its position.

Let's start with the canvas. There are basically two types of instructions that we can add to a canvas: vertex instructions and context instructions.

Note

The vertex instructions inherit from the VertexInstruction base class, and allow us to draw vector shapes in the coordinate space.

The context instructions...

Adding images, colors, and backgrounds


In this section, we will discuss how to add images and colors to our graphics and how to control which graphic comes on top of which one. We continue using the same Python code of the first section. This time, we run it with a 400 x 100 screen size: python drawing.py --size=400x100. The following screenshot shows the final result of this section:

Images and Colors

The following is the corresponding drawing.kv code:

64. # File name: drawing.kv (Images and colors)
65. <DrawingSpace>:
66.     canvas:
67.         Ellipse:
68.            pos: 10,10
69.            size: 80,80
70.            source: 'kivy.png'
71.         Rectangle:
72.            pos: 110,10
73.            size: 80,80
74.            source: 'kivy.png'
75.        Color: 
76.            rgba: 0,0,1,.75
77.        Line:
78.            points: 10,10,390,10
79.            width: 10
80.            cap: 'square'
81.          Color: 
82.            rgba: 0,1,0,1
83.        Rectangle:
84.     ...

Structuring graphic instructions


Apart from the canvas instance, a Widget includes two other canvas instances: canvas.before and canvas.after.

Note

The Widget class has three sets of instructions (canvas.before, canvas, and canvas.after) to organize the order of execution. With them, we can control which elements will go to the background or stay on the foreground.

The following drawing.kv file shows an example of these three sets (lines 92, 98, and 104) of instructions:

90. # File name: drawing.kv (Before and After Canvas)
91. <DrawingSpace>:
92.    canvas.before:
93.        Color: 
94.            rgba: 1,0,0,1
95.        Rectangle:
96.            pos: 0,0
97.            size: 100,100
98.    canvas:
99.        Color: 
100.         rgba: 0,1,0,1
101.     Rectangle:
102.         pos: 100,0
103.         size: 100,100
104.  canvas.after:
105.      Color: 
106.          rgba: 0,0,1,1
107.      Rectangle:
108.          pos: 200,0
109.          size: 100,100
110.  Button:
111.      text: 'A...

Rotating, translating, and scaling the coordinate space


Rotate, Translate, and Scale are context instructions that are applied to the vertex instructions, which are displayed in the coordinate space. They could bring unexpected results if we forget that the coordinate space is shared among all widgets, and it occupies the size of the window (actually bigger than that because there is no restriction on the coordinates and we can draw outside the window). First, we are going to understand the behavior of this instruction in this section and, in the next section, we can analyze the problems they bring in a deeper way, and learn techniques to make things easier.

Let's start with the new drawing.kv code:

114. # File name: drawing.kv (Rotate, Translate and Scale)
115. <DrawingSpace>:
116.    pos_hint: {'x':.5, 'y':.5}
117.    canvas:
118.        Rectangle:
119.            source: 'kivy.png'
120.        Rotate:
121.            angle: 90
122.            axis: 0,0,1
123.        Color:
124. ...

Comic Creator: PushMatrix and PopMatrix


Let's insert some graphics to the project we started in Chapter 1, GUI Basics – Building an Interface. Before this, we need to recapitulate two important lessons of this chapter related to the coordinate space:

  • The coordinate space is not restricted to any position or size. It normally has its origin in the bottom-left corner of the screen. To avoid this, we use RelativeLayout, which internally performs a translation to the position of the Widget.

  • Once the coordinate space context is transformed by any instruction, it stays like that until we specify something different. RelativeLayout also addresses this problem with two contextual instructions, which we will study in this section: PushMatrix and PopMatrix.

We use RelativeLayout in this section to avoid the problems of the shared coordinate space, but we will also explain the alternatives to it when we are inside any other type of Widget. We will add a new file (comicwidgets.kv) to our project. In comicreator...

Summary


This chapter explained the necessary concepts to understand the use of the canvas. We covered the use of vertex and context instructions, and how to manipulate the order of the execution of instructions. We covered how to deal with the transformation of canvas, either reversing all the transformations or using RelativeLayout. The following is the whole set of components we learnt to use, in this chapter:

  • The vertex instructions (and many of their respective properties): Rectangle (pos, size), Ellipse (pos, size, angle_start, angle_end, segments), Triangle (points), Quad (points), Point (points, pointsize), Line (points, ellipse, circle, rectangle, width, close, dash_lenght, dash_offset, and cap), Bezier (points, segments, dash_lenght, and dash_offset,), and Mesh (mode, vertices, indices)

  • The source property that applies to all the vertex instructions

  • The three set of canvas instructions: canvas.before, canvas, and canvas.after

  • The context instructions (and some of their properties)...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Kivy - Interactive Applications and Games in Python
Published in: Jun 2015Publisher: ISBN-13: 9781785286926
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Roberto Ulloa

Roberto Ulloa has a diverse academic record in multiple disciplines within the field of computer science. Currently, he is working with artificial societies as part of his PhD thesis at the University of Western Ontario. He obtained an MSc degree from the University of Costa Rica and taught programming and computer networking there. He has earned a living as a web developer, working with Python/Django and PHP/Wordpress. He collaborates with various researchers while also working on his own projects, including his blog (http://robertour.com). He constantly worries that the Internet has already become aware of itself and that we are not able to communicate with it because of the improbability of it being able to speak any of the 6,000-plus odd human languages that exist on the planet.
Read more about Roberto Ulloa