- Kivy:Interactive Applications and Games in Python(Second Edition)
- Roberto Ulloa
- 1847字
- 2021-07-16 14:07:28
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 (Color
, Rotate
, Translate
, and Scale
) inherit from the ContextInstruction
base class, and let us apply transformations to the coordinate space context. By coordinate space context, we mean the conditions in which the shapes (specified in the vertex instructions) are drawn in the coordinate space.
Basically, vertex instructions are what we draw and context instructions affect where and how we draw. The following is the screenshot for the first example of this chapter:

In the preceding screenshot, the gray grid will simplify reading the coordinates that appear in the code. Also, the white letters associated with each cell will be used to refer to the shapes. Neither the grid nor the letters are part of the Kivy example. The preceding screenshot illustrates 10 basic figures that we learn to draw with vertex instructions. Almost all the available Kivy classes are represented in this example and we can create any 2D geometric shape with them. Since the vertex instructions use fixed coordinates, it is important to run this example with a screen size of 500 x 200 (python drawing.py --size=500x200
) in order to visualize the shapes correctly.
We will study the Kivy language (drawing.kv
) with small code fragments associated to the respective figure (and coordinates) next to it, so it would be easier to follow. Let's start with the shape A (rectangle):

Following is the code snippet for shape A:
14. # File name: drawing.kv (vertex instructions) 15. <DrawingSpace>: 16. canvas: 17. Rectangle: 18. pos: self.x+10,self.top-80 19. size: self.width*0.15, self.height*0.3
Rectangle
is a good starting point because it resembles the way we set properties in widgets. We just have to set the pos
and size
properties.
Note
The pos
and size
properties of the vertex instructions are different from the pos
and size
properties of Widget
, since they belong to the VertexInstruction
base class. All the values to specify the properties of the vertex instructions are given in fixed values.
This means that we cannot use the size_hint
or pos_hint
properties as we did with the widgets in Chapter 1, GUI Basics – Building an Interface. However, we can use the properties of self
to achieve similar results (Line 18 and 19).
Let's proceed with the shape B (Pac-Man-like figure):

Following is the code snippet for shape B:
20. Ellipse: 21. angle_start: 120 22. angle_end: 420 23. pos: 110, 110 24. size: 80,80
The Ellipse
works very similar to Rectangle
, but it has three new properties: angle_start
, angle_end
, and segments
. The first two properties specify the initial and final angle of the ellipse. The angle 0° is North (or 12 o'clock) and they add up in the clockwise direction. So, the angle_start
is 120° (90° + 30°), which is the lower jaw of the Pac-Man-like figure (Line 21). The angle_end
value is 420° (360° + (90°-30°)), which is bigger than angle_start
because we need Kivy to follow the clockwise direction to paint the Ellipse
. If we specify a lower value than angle_start
, Kivy will follow a counter clockwise direction, painting where the mouth of the Pac-Man is, instead of its body.
Let's continue with the shape C (triangle):

25. Ellipse: 26. segments: 3 27. pos: 210,110 28. size: 60,80
The triangle of shape C is actually another Ellipse
that we obtain thanks to the segments
property (Line 26). Let's put it this way: if you have to draw an ellipse with three lines, the best you would end up with is a triangle. If you have four lines, you would end up with a rectangle. You actually need infinite lines for a perfect Ellipse
, but a computer cannot process that (neither the screen has enough resolution to support this), so we need to stop at some point. The default segments
are 180. Notice that if you have a circle (that is, size: x,x), you will always get equilateral polygons (for example, a square if you specify just four segments
).
We can analyze shapes D, E, F, and G together:

29. Triangle: 30. points: 310,110,340,190,380,130 31. Quad: 32. points: 410,110,430,180,470,190,490,120 33. Line: 34. points: 10,30, 90,90, 90,10, 10,60 35. Point: 36. points: 110,30, 190,90, 190,10, 110,60 37. pointsize: 3
Triangle
(shape D), Quad
(shape E), and Line
(shape F) work similarly. Their points
property (Lines 30, 32, and 34) indicates the corners of a triangle, quadrilateral, and a line, respectively. The points
property is a sequence of coordinates in the format (x1, y1, x2, y2)
. Point
is also similar to these three shapes. It uses the points
property (Line 36) but in this case to indicate a sequence of points (shape G). It also uses the pointsize
(Line 37) property to indicate the size of the Points
.
Let's proceed with the shape H:

38. Bezier: 39. points: 210,30, 290,90, 290,10, 210,60 40. segments: 360 41. dash_length: 10 42. dash_offset: 5
Bezier
is a curved line that uses the points
property as a set of 'attractors' of the curve line (there is a math formalism behind Bézier curves that we are not going to cover in this book because it is out of its scope, but you can find enough information in Wikipedia http://en.wikipedia.org/wiki/Bézier_curve). The points are attractors because the line does not touch all of them (just the first and the last of them). The points of Bezier
(Line 39) are at the same distance from each other as the points of the Line
(Line 34), or the Point
(Line 36); they were just translated 100 pixels to the right. You can visually compare the result of the Bezier curve (shape H), with the results of the Line
(shape G) or the Point
(shape H). We included two other properties dash_length
(Line 41), for the length of the dashes of the discontinuous line, and dash_offset
(Line 42) for the distance between the dashes.
Let's cover the last shapes I and J:

43. Mesh: 44. mode: 'triangle_fan' 45. vertices: 310,30,0,0, 390,90,0,0, 390,10,0,0, 310,60,0,0 46. indices: 0,1,2,3 47. Mesh: 48. mode: 'triangle_fan' 49. vertices: 430,90,0,0, 470,90,0,0, 490,70,0,0, 450,10,0,0, 410,70,0,0, 430,90,0,0, 50. indices: 0,1,2,3,4,5
We added two Mesh
instructions (Lines 43 and 47). A Mesh
instruction is a compound of triangles and has many applications in computer graphics and games. There is not enough space in this book to cover the advanced techniques to use this instruction, but at the very least we will understand its basics and be able to draw flat polygons. The mode
property is set to triangle_fan
(Line 44), which means that the triangles of the mesh are filled with color, instead of, for example, just drawing the border.
The vertices
property is a tuple of coordinates. For the purpose of this example, we will just ignore all the 0s. This will leave us with four coordinates (or vertices) in line 45. These points are relatively the same as shapes F, G, and H. Let's imagine for the shape I how the triangles are created as we traverse them, left to right on the vertex list using three vertex points each time. The shape I is composed of two triangles. The first triangle uses the first, second, and third vertices; and the second triangle uses the first, third, and fourth vertices. In general, if we are in the ith vertex of the list, a triangle is drawn using the first vertex, the (i-1)th vertex, and the ith vertex. The final mesh (shape J) presents another example. It contains three triangles that are surrounded by a blue line in the following screenshot:

The indexes
property contains a list with the same number of vertices (not counting the 0s) and instructs the order in which the vertices list is traversed, altering the triangles that compose the mesh.
So far, all the polygons that we studied have been colored in. If we need to draw the border of the polygon, we should use Line
instead. In principle, this seems easy for a basic shape such as a triangle, but how do we draw a circle with just points? Fortunately, Line
has the appropriate properties to make things easier.
The next example will show how you can build the figures in the following screenshot:

Line examples
We have kept the gray coordinates and the letter to identify each cell in the screenshot. The Python code should be run in a screen size of 400 x 100: python drawing.py --size=400x100
. The following is the drawing.kv
code for the previous screenshot:
51. # File name: drawing.kv (Line Examples) 52. <DrawingSpace>: 53. canvas: 54. Line: 55. ellipse: 10, 20, 80, 60, 120, 420, 180 56. width: 2 57. Line: 58. circle: 150, 50, 40, 0, 360, 180 59. Line: 60. rectangle: 210,10,80,80 61. Line: 62. points: 310,10,340,90,390,20 63. close: True
In the previous code, we added four Line
instructions using specific properties. The first Line
instruction (in line 54, shape A) is similar to our Pac-Man (line 20). The ellipse
property (line 55) specifies x
, y
, width
, height
, angle_start
, angle_end
, and segments
, respectively. The order of the parameters is difficult to remember so we should always keep the Kivy API next to us (http://kivy.org/docs/api-kivy.graphics.vertex_instructions.html). We also set width
of Line
to make it thicker (line 56).
The second Line
instruction (line 57, shape B) introduces a property that has no counterpart in the vertex instructions: circle
. The difference with the ellipse
property is that the first three parameters (line 58) define the center (150, 50) and radius (40) of Circle
. The rest remains the same. The third Line
(line 59, shape C) is defined by rectangle
(line 60) and the parameters are simply x
, y
, width
, and height
. The last Line
(line 61, shape D) is the most flexible way to define polygons. We specified the points (line 62), as many as we want. The close
property (line 63) connects the first and last points.
We covered most of the instructions and properties related to vertex instructions. We should be able to draw any geometrical shape in two dimensions with Kivy. If you want more details about each of the instructions, you should visit the Kivy API (http://kivy.org/docs/api-kivy.graphics.vertex_instructions.html). Now, it is the turn of context instructions to decorate these boring black and white polygons.
- Python數(shù)據(jù)分析基礎(chǔ)
- 深入淺出Windows API程序設(shè)計(jì):編程基礎(chǔ)篇
- 深入淺出RxJS
- SQL Server 2016數(shù)據(jù)庫(kù)應(yīng)用與開(kāi)發(fā)習(xí)題解答與上機(jī)指導(dǎo)
- SharePoint Development with the SharePoint Framework
- Mastering Linux Network Administration
- Python忍者秘籍
- Getting Started with LLVM Core Libraries
- C專(zhuān)家編程
- 深入分析GCC
- 例說(shuō)FPGA:可直接用于工程項(xiàng)目的第一手經(jīng)驗(yàn)
- 基于MATLAB的控制系統(tǒng)仿真及應(yīng)用
- Python網(wǎng)絡(luò)爬蟲(chóng)從入門(mén)到實(shí)踐
- Windows 10 for Enterprise Administrators
- AngularJS by Example