source: nagslang/widgets/text.py@ 237:6995dbefdbfb

Last change on this file since 237:6995dbefdbfb was 237:6995dbefdbfb, checked in by Neil Muller <drnlmuller@…>, 8 years ago

Add multiline widget

File size: 2.7 KB
RevLine 
[237]1from nagslang.constants import FONT, FONT_SIZE
2from nagslang.widgets.base import Widget
[196]3import pygame
4
[29]5from nagslang.utils import convert_colour
[33]6from nagslang.resources import resources
[29]7
8
9class TextWidget(Widget):
10 def __init__(self, pos, text, size=None, fontname=None, fontsize=None,
11 colour=None):
12 super(TextWidget, self).__init__(pos, size)
13
14 self.text = text
15 self.fontname = fontname or FONT
16 self.fontsize = fontsize or FONT_SIZE
17 self.colour = convert_colour(colour or (0, 0, 0))
18
19 self.prepare()
20
21 def prepare(self):
[33]22 self.font = resources.get_font(self.fontname, self.fontsize)
[29]23 self.surface = self.font.render(self.text, True, self.colour)
24 self.text_rect = self.surface.get_rect()
25 if not self.size:
26 self.rect.size = self.text_rect.size
27
28 def draw(self, surface):
29 if self.visible:
30 self.do_prepare()
31 surface.blit(self.surface, self.rect)
[196]32
33
[237]34class MultiLineWidget(TextWidget):
35
36 def prepare(self):
37 self.font = resources.get_font(self.fontname, self.fontsize)
38 surfaces = []
39 height = 0
40 width = 0
41 for line in self.text.split('\n'):
42 surface = self.font.render(line, True, self.colour)
43 width = max(width, surface.get_rect().width)
44 height += surface.get_rect().height
45 surfaces.append(surface)
46 self.surface = pygame.surface.Surface((width, height))
47 self.surface.fill(pygame.Color('white'))
48 y = 0
49 for surface in surfaces:
50 self.surface.blit(surface, (0, y))
51 y += surface.get_rect().height
52
53
[196]54class LabelWidget(TextWidget):
55 def __init__(self, *args, **kwargs):
56 self.padding = kwargs.pop('padding', 5)
57 self.border = kwargs.pop('border', 2)
58 self.bg_colour = convert_colour(kwargs.pop('bg_colour',
59 (255, 255, 255, 150)))
60 self.border_colour = convert_colour(kwargs.pop('border_colour',
61 (0, 0, 0)))
62 super(LabelWidget, self).__init__(*args, **kwargs)
63
64 def prepare(self):
65 super(LabelWidget, self).prepare()
66 if not self.size:
67 self.rect.width += 2 * self.padding
68 self.rect.height += 2 * self.padding
69 surface = pygame.Surface(self.rect.size)
70 surface = surface.convert_alpha()
71 surface.fill(self.bg_colour)
72 surface.blit(self.surface, self.surface.get_rect().move(
73 (self.padding, self.padding)))
74 pygame.draw.rect(surface, self.border_colour, surface.get_rect(),
75 self.border)
76 self.surface = surface
Note: See TracBrowser for help on using the repository browser.