Passed
Pull Request — master (#21)
by Matt
03:47 queued 01:54
created

PyDMXControl.design.parts._Text   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 39
dl 0
loc 60
rs 10
c 0
b 0
f 0
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A Text.design_render() 0 29 3
A Text.__init__() 0 12 1
1
"""
2
 *  PyDMXControl: A Python 3 module to control DMX using uDMX.
3
 *                Featuring fixture profiles, built-in effects and a web control panel.
4
 *  <https://github.com/MattIPv4/PyDMXControl/>
5
 *  Copyright (C) 2018 Matt Cowley (MattIPv4) ([email protected])
6
"""
7
8
from math import floor
9
from typing import Union, List, Tuple
10
11
import pygame
12
13
from ._Part import Part
14
15
16
class Text(Part):
17
18
    def __init__(self, x: Union[int, float], y: Union[int, float], text: str, *,
19
                 scale: Union[int, float] = 1, color: Union[List[int], Tuple[int, int, int]] = (0, 0, 0),
20
                 background_color: Union[List[int], Tuple[int, int, int], None] = (255, 255, 255, int(255 * 0.95)),
21
                 align_left: bool = False):
22
        super().__init__()
23
        self.__text = text
24
        self.__scale = scale
25
        self.__color = color
26
        self.__bg_color = background_color
27
        self.__left = align_left
28
        self.__font = pygame.font.SysFont("monospace", int(24 * self.__scale), bold=True)
29
        self.set_pos(x, y)
30
31
    def design_render(self, screen: 'Screen') -> Tuple[int, int, pygame.Surface]:
32
        # Generate text
33
        text = self.__font.render(self.__text, True, self.__color)
34
35
        # Resize text
36
        tx, ty = text.get_size()
37
        text = pygame.transform.scale(text, (
38
            int(tx * screen.block_size * 0.15),
39
            int(ty * screen.block_size * 0.15)
40
        ))
41
42
        # Generate background
43
        if self.__bg_color is not None:
44
            padding = screen.block_size * 0.25
45
            tx, ty = text.get_size()
46
            surface = pygame.Surface((int(tx + padding * 2), int(ty + padding * 2)), pygame.SRCALPHA, 32)
47
            surface = surface.convert_alpha()
48
            surface.fill(self.__bg_color)
49
            surface.blit(text, (padding, padding))
50
        else:
51
            surface = text
52
53
        # Render
54
        x, y = surface.get_size()
55
        x = int((self._x * screen.block_size) - floor(x / 2))
56
        y = int((self._y * screen.block_size) - floor(y / 2))
57
        if self.__left:
58
            x = int(self._x * screen.block_size)
59
        return x, y, surface
60