1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
# -*- coding: utf-8 -*-
import pygame
font_path = 'assets/fonts/'
class CLabel(pygame.sprite.Sprite):
""" a basic label
properties:
font: font to use
text: text to display
fgColor: foreground color
bgColor: background color
center: position of label's center
size: (width, height) of label
"""
def __init__(self, fontName = "DejaVuSans.ttf", transparent=False):
pygame.sprite.Sprite.__init__(self)
self.font = pygame.font.Font(font_path + fontName, 20)
self.text = ""
self.fgColor = (0x00, 0x00, 0x00)
self.bgColor = (0xFF, 0xFF, 0xFF)
self.transparent = transparent
self.center = (0, 0)
self.size = (0, 0)
def set_font(self, fontName = "DejaVuSans.ttf", fontSize= 20):
self.font = pygame.font.Font(font_path + fontName, fontSize)
self._update_image()
def set_center(self, aCenter):
self.center = aCenter
def set_size(self, aSize):
self.size = aSize
self._update_image()
def set_fgColor(self, afgColor):
if not(self.fgColor == afgColor):
self.fgColor = afgColor
self._update_image()
def set_bgColor(self, abgColor):
if not(self.bgColor == abgColor):
self.bgColor = abgColor
self._update_image()
def set_text(self, aText):
self.text = aText
self._update_image()
def _update_image(self):
self.image = pygame.Surface(self.size)
self.image.fill(self.bgColor)
if self.transparent:
self.image.set_colorkey(self.bgColor)
fontSurface = self.font.render(self.text, True, self.fgColor)
else:
fontSurface = self.font.render(self.text, True, self.fgColor, self.bgColor)
#center the text
xPos = (self.image.get_width() - fontSurface.get_width())/2
self.image.blit(fontSurface, (xPos, 0))
self.update()
def update(self):
self.rect = self.image.get_rect()
self.rect.center = self.center
def destroy(self):
self.font = None
self.image = None
|