Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #61297 > unrolled thread

Re: Centring text in a rect in PyGame?

Started byTim Golden <mail@timgolden.me.uk>
First post2013-12-08 15:42 +0000
Last post2013-12-08 15:42 +0000
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Centring text in a rect in PyGame? Tim Golden <mail@timgolden.me.uk> - 2013-12-08 15:42 +0000

#61297 — Re: Centring text in a rect in PyGame?

FromTim Golden <mail@timgolden.me.uk>
Date2013-12-08 15:42 +0000
SubjectRe: Centring text in a rect in PyGame?
Message-ID<mailman.3731.1386517367.18130.python-list@python.org>
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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web