view mamba/widgets/text.py @ 91:ebd8f46cc553

Text Button
author Stefano Rivera <stefano@rivera.za.net>
date Sun, 11 Sep 2011 19:05:20 +0200
parents ac6688820528
children d5aa5f805f00
line wrap: on
line source

import pygame

from mamba.widgets.base import Widget
from mamba.data import filepath
from mamba.constants import DEFAULT_FONT

class TextWidget(Widget):
    fontcache = {}

    def __init__(self, rect, text, fontsize=16, color='black'):
        super(TextWidget, self).__init__(rect)
        self.text = text
        self.fontsize = fontsize
        self.color = color
        self.prepare()

    def prepare(self):
        self.fontname = DEFAULT_FONT
        font = (self.fontname, self.fontsize)
        if font not in TextWidget.fontcache:
            fontfn = filepath('fonts/' + self.fontname)
            TextWidget.fontcache[font] = pygame.font.Font(fontfn, self.fontsize)
        self.font = TextWidget.fontcache[font]
        if not isinstance(self.color, pygame.Color):
            self.color = pygame.Color(self.color)
        self.surface = self.font.render(self.text, True, self.color)
        self.rect.width, self.rect.height = self.surface.get_rect().size

    def draw(self, surface):
        surface.blit(self.surface, self.rect)


class TextButton(TextWidget):
    def __init__(self, *args, **kwargs):
        self.focus_color = kwargs.pop('focus_color', 'red')
        self.padding = kwargs.pop('padding', 10)
        self.border = kwargs.pop('border', 3)
        super(TextButton, self).__init__(*args, **kwargs)
        if not isinstance(self.focus_color, pygame.Color):
            self.focus_color = pygame.Color(self.focus_color)
        self.focussable = True

    def prepare(self):
        super(TextButton, self).prepare()
        text = self.surface
        text_rect = text.get_rect()
        self._focussed = self.focussed
        color = self.focus_color if self.focussed else self.color

        self.rect.width = text_rect.width + self.padding * 2
        self.rect.height = text_rect.height + self.padding * 2
        self.surface = pygame.Surface(self.rect.size)
        self.surface.blit(text, text.get_rect().move(self.padding,
                                                     self.padding))
        pygame.draw.rect(self.surface, color, self.surface.get_rect(),
                         self.border)

    def draw(self, surface):
        if self._focussed != self.focussed:
            self.prepare()
        super(TextButton, self).draw(surface)