0

UIText is a subclass of pygame.sprite.Sprite. I would like to change the scale of each text component, similar to how normal sprites can be scaled:

ui_element.rect.width = ui_element.parent_screen.rect.width * self.width_percent
ui_element.image = pg.transform.smoothscale(ui_element.original_image, ui_element.rect.size)

The problem with scaling this text component with the above method is that since UIText has a different image, setting it to pg.transform.smoothscale gets rid of the text, and turns it into a rect.

class UIText(UIComponent):

    def __init__(self, text="Hello :)"):
        super().__init__()
        self.text = text
        self.size = 12
        self.update_text()

    def set_text(self, text):
        self.text = text

    def set_size(self, size):
        self.size = size
        self.update_text()

    def update_text(self):
        font = pg.font.SysFont("gothicI", self.size, self.bold, self.italic)
        self.image = font.render(str(self.text), 1, self.colour)
        self.rect = self.image.get_rect()
Hydra
  • 373
  • 3
  • 18
  • 1
    Does this answer your question? [How to scale the font size in pygame based on display resolution?](https://stackoverflow.com/questions/56855775/how-to-scale-the-font-size-in-pygame-based-on-display-resolution) – totok Jul 23 '20 at 07:03

1 Answers1

0

I think this is what you want. pygame.font.Font.render() returns an instance of pygame.Surface, which you can squash and stretch to your own satisfaction.

class UIText(UIComponent):

    def __init__(self, text="Hello"):
        super().__init__()
        self.text = text
        self.size = 12

        self.update_text()

    def set_text(self, text):
        self.text = text

    def set_scale(self, scale: tuple):  # (width, height)
        self.image = pygame.transform.scale(self.image, scale)

    def set_size(self, size: int):
        self.size = size
        self.update_text()

    def update_text(self):
        font = pg.font.SysFont("gothicI", self.size, self.bold, self.italic)
        self.image = font.render(str(self.text), 1, self.colour)
        self.rect = self.image.get_rect()