Search code examples
pythonpygamecentering

pygame blitting - center


I am trying to make a script in python for pygame to draw a button with text centered, but when I blit onto the screen, it blits to the x and y I give it, not a proportionally centered location. I want to be able to center it to a set of (x,y,w,h). How would I do this? Here's my code:

# Imports
import pygame

class Text:
    'Centered Text Class'
    # Constructror
    def __init__(self, text, (x,y,w,h), color = (0,0,0)):
        self.x = x
        self.y = y
        self.w = w
        self.h = h
        # Start PyGame Font
        pygame.font.init()
        font = pygame.font.SysFont("sans", 20)
        self.txt = font.render(text, True, color)
    # Draw Method
    def Draw(self, screen):
        coords = (self.x, self.y)
        screen.blit(self.txt, coords)

Edit: Comments, yes I know but I only used x and y as temporary variables because I have no idea what the centered x and y would be to center the text. (I want to know how to center its CENTER to a rect, not its top left corner)


Solution

  • You'll want to use the font.size() method to determine how large the rendered text will be.

    Something like:

    class Text:
        """Centered Text Class"""
        # Constructror
        def __init__(self, text, (x,y), color = (0,0,0)):
            self.x = x #Horizontal center of box
            self.y = y #Vertical center of box
            # Start PyGame Font
            pygame.font.init()
            font = pygame.font.SysFont("sans", 20)
            self.txt = font.render(text, True, color)
            self.size = font.size(text) #(width, height)
        # Draw Method
        def Draw(self, screen):
            drawX = self.x - (self.size[0] / 2.)
            drawY = self.y - (self.size[1] / 2.)
            coords = (drawX, drawY)
            screen.blit(self.txt, coords)