sep-pm-platformer/project/ui_elements/TextLabel.py

57 lines
2.1 KiB
Python

import pygame
from pygame import Surface
from pygame.font import Font
from physics.TickData import TickData
from sprite.BoundingBox import BoundingBox
from sprite.PositionScale import PositionScale
from ui_elements.UiElement import UiElement
class TextLabel(UiElement):
def tick(self, tick_data: TickData):
pass
def __init__(self, text: str, x_position: float, y_position: float, font_size: int = 50, alignment: str = "left"):
super().__init__()
self.text = text
self.x_position = x_position
self.y_position = y_position
self.current_width = 0
self.current_height = 0
self.alignment = alignment
self.font_size = font_size
self.font = Font('data/font/MilkyNice.ttf', self.font_size)
def render_sprite_image(self) -> pygame.Surface:
return self.font.render(str(self.text), True, pygame.Color('white'))
def draw(self, screen: Surface, screen_transform: PositionScale):
rendered_font = self.font.render(str(self.text), True, pygame.Color('white'))
self.current_width = rendered_font.get_width()
self.current_height = rendered_font.get_height()
if self.alignment == "right":
self.position_scale.position = (self.x_position - self.current_width, self.y_position)
elif self.alignment == "left":
self.position_scale.position = (self.x_position, self.y_position)
elif self.alignment == "center":
self.position_scale.position = (self.x_position - self.current_width / 2, self.y_position)
super().draw(screen, screen_transform)
def set_text(self, new_text: str):
self.text = new_text
def get_bounding_box(self) -> BoundingBox:
return BoundingBox(
self.position_scale.position[0] - self.bounding_box_margin[0],
self.position_scale.position[1] - self.bounding_box_margin[1],
self.current_width * self.position_scale.scale[0] + self.bounding_box_margin[0] * 2,
self.current_height * self.position_scale.scale[1] + self.bounding_box_margin[1] * 2
)