Re: Centring text in a rect in PyGame?

Discussion in 'Python' started by Tim Golden, Dec 8, 2013.

  1. Tim Golden

    Tim Golden Guest

    On 07/12/2013 12:41, Eamonn Rea wrote:
    > Anyway, I have a problem. In my game, I want to draw a button. I’ve
    > gotten the button to draw fine, but I want some text on the button. I’ve
    > gotten the text to draw, but I can’t get it to centre into the button.
    > Here’s the code I’ve used:
    >
    > *self.surface.blit(self.button_text, (self.width / 2 -
    > self.button_text.get_width() / 2, self.height / 2 -
    > self.button_text.get_height() / 2))*


    Side-stepping your actual code, here's a handy thing in pygame. You can
    center one rect on another to achieve the same effect without bothering
    with the (x - y) / 2 stuff.

    import pygame
    pygame.init()

    #
    # For demo purposes, the button is the whole window
    #

    button = pygame.display.set_mode((400, 320))

    #
    # Create 12-point text in white saying "Hello, World!"
    #
    font = pygame.font.Font(pygame.font.get_default_font(), 12)
    text = font.render("Hello, World!", True, (0xff, 0xff, 0xff))

    #
    # Use the text's rect to get width / height
    # Then center that rect on the target surface
    #
    text_rect = text.get_rect()
    text_rect.center = button.get_rect().center
    button.blit(text, text_rect)

    pygame.display.flip()



    TJG
     
    Tim Golden, Dec 8, 2013
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. bunty

    RECt Structure Problem

    bunty, Jul 6, 2006, in forum: C++
    Replies:
    9
    Views:
    416
    Jerry Coffin
    Jul 14, 2006
  2. globalrev

    pygame: rect moveto?

    globalrev, May 3, 2008, in forum: Python
    Replies:
    1
    Views:
    337
    Marc 'BlackJack' Rintsch
    May 3, 2008
  3. rantingrick

    [pygame-bug] Pygame.cdrom bug

    rantingrick, Jan 30, 2011, in forum: Python
    Replies:
    1
    Views:
    307
    Benjamin Kaplan
    Jan 30, 2011
  4. Scott Siegler

    pygame.Rect question

    Scott Siegler, Apr 9, 2012, in forum: Python
    Replies:
    1
    Views:
    313
    Peter Pearson
    Apr 9, 2012
  5. Tim Golden

    Re: Centring text in a rect in PyGame?

    Tim Golden, Dec 8, 2013, in forum: Python
    Replies:
    1
    Views:
    80
Loading...

Share This Page