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

48 lines
1.9 KiB
Python
Raw Normal View History

2023-03-25 15:41:32 +01:00
import pygame
2023-03-25 18:11:41 +01:00
from pygame import Surface, Rect
2023-03-25 15:41:32 +01:00
from pygame.font import Font
from sprite.PositionScale import PositionScale
class TextLabel:
2023-03-25 18:11:41 +01:00
def __init__(self, text: str, x_position: float, y_position: float, font_size: int,
2023-03-25 15:41:32 +01:00
alignment: str = "left"):
self.text = text
self.x_position = x_position
self.y_position = y_position
self.alignment = alignment
self.current_width = 0
self.current_height = 0
self.font_size = font_size
2023-03-25 18:11:41 +01:00
self.font = Font('data/font/MilkyNice.ttf', self.font_size)
2023-03-25 15:41:32 +01:00
self.position_scale = PositionScale()
2023-03-25 16:18:44 +01:00
def draw(self, screen: Surface, screen_transform: PositionScale):
2023-03-25 18:11:41 +01:00
rendered_font = self.font.render(str(self.text), True, pygame.Color('white'))
2023-03-25 15:41:32 +01:00
self.current_width = rendered_font.get_width()
self.current_height = rendered_font.get_height()
if self.alignment == "right":
2023-03-25 18:11:41 +01:00
screen.blit(rendered_font, (self.x_position - self.current_width, self.y_position))
elif self.alignment == "left":
2023-03-25 15:41:32 +01:00
screen.blit(rendered_font, (self.x_position, self.y_position))
elif self.alignment == "center":
2023-03-25 18:11:41 +01:00
screen.blit(rendered_font, (self.x_position - self.current_width / 2, self.y_position))
target_scale = (screen_transform.scale[0] * self.position_scale.scale[0],
screen_transform.scale[1] * self.position_scale.scale[1])
target_position = ((self.position_scale.position[0] + screen_transform.position[0]) * target_scale[0],
(self.position_scale.position[1] + screen_transform.position[1]) * target_scale[1])
target_size = (int(target_scale[0] * self.x_position),
int(target_scale[1] * self.y_position))
target_image = pygame.transform.scale(rendered_font, target_size)
2023-03-25 15:41:32 +01:00
2023-03-25 18:11:41 +01:00
def set_text(self, new_text: str):
self.text = new_text