A Text Object
In example 2b we wrapped our image loading function in an object for
convenience and additional functionality. Now we will do the same
for the text loading function from example 3a.
Because the results of loading an image and loading a font are very
similar it makes sense to wrap them both in very similar objects.
So we create a Text object that inherits from Image, and uses
Image's draw and destructor functions directly.
1 from Image import Image
2 import gutil
3
4 class Text(Image):
5
6 def __init__(self, text, fontsize = 24, color = (0,0,0,0), font = None, antialias = 1):
7 texttexture = gutil.loadText(text, fontsize, color, font, antialias)
8 self.texture = texttexture[0]
9 self.width = texttexture[1]
10 self.height = texttexture[2]
11 self.texture_width = texttexture[3]
12 self.texture_height = texttexture[4]
13 self.displayList = gutil.createTexDL(self.texture, self.texture_width, self.texture_height)
The init method takes roughly the same arguments that the loadText
function takes. It calls the loadText function, stores the
texture id, the text image size, and the actual OpenGL texture size.
It then creates a display list.
Because we are storing the same information, we do not need to define
destructor or draw methods. The Image class takes care of this
for us.
Now lets look at an example using the new class.
1 #!/usr/bin/python
2
3 import gutil
4 import pygame
5 from pygame.locals import *
6 from OpenGL.GL import *
7
8 from Image import Image
9 from Text import Text
10
11
12 def main():
13 pygame.init()
14 gutil.initializeDisplay(800, 600)
15
16 done = False
17
18 cow = Image('cow')
19 alien = Image('alien')
20
21 white = (255,255,255,255)
22 string1 = Text("Cow!", fontsize=256, color=white)
23 string2 = Text("Rotation!", color=white)
24
25 while not done:
26 glClear(GL_COLOR_BUFFER_BIT)
27 cow.draw(pos=(100,100),width=128,height=128)
28 string1.draw(pos=(100,0), width=128,height=128)
29 alien.draw(pos=(400, 400),rotation=-15,color=(.9,.3,.2,1))
30 string2.draw(pos=(600, 400), rotation=20, color=(.2,.3,.9,1))
31
32 pygame.display.flip()
33
34 eventlist = pygame.event.get()
35 for event in eventlist:
36 if event.type == QUIT \
37 or event.type == KEYDOWN and event.key == K_ESCAPE:
38 done = True
39
40 if __name__ == '__main__':
41 main()
Very little has changed here from previous examples. We import
the new class on line 9. We create two Text objects on lines 22
and 23, and we draw these two objects on lines 28 and 30.
Up to the Index
Back to Example 3a