1
0

More than 1 year has passed since last update.

pygameでテキストを中央寄せにする

Last updated at Posted at 2021-10-22

いろいろ調べてもやり方がよく分からず、分解して考えることで理解できる気がしたのでまとめてみた。
全体像はこんな感じ。

import pygame

WIDTH = 500
HEIGHT = 500

pygame.init()

screen = pygame.display.set_mode((WIDTH, HEIGHT))
font = pygame.font.SysFont(None, 120)

text = font.render("Test", False, (255,255,255))
text_rect = text.get_rect(center=(WIDTH//2, HEIGHT//2))

endFlag = False
while endFlag == False:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            endFlag = True
    screen.blit(text, text_rect)
    pygame.display.update()

pygame.quit()

動かしてみるとこんな感じになる。
スクリーンショット 2021-10-22 21.19.45.png

逆から重要なところだけ抜き取って読み解いていく

screen.blit(画像, (x,y))


画像と位置が必要

まずは画像を用意(テキストをレンダリングして画像とする)

text = font.render("Test", False, (255,255,255))


このレンダリングされた情報を元に中央の位置を決める

text_rect = text.get_rect(center=(WIDTH//2, HEIGHT//2))

見ての通りWIDTH//2で横の中央、HEIGHT//2で縦の中央の位置を取得できる。

結局人から見てわかりやすいものができたかは分からないがとりあえず動くので自分はこれで覚えることにする。

1
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0