我试图用python编写一个脚本,让pygame绘制一个以文本为中心的按钮,但是当我闪到屏幕上时,它会闪到我给出的x和y,而不是按比例居中的位置。我想把它放在(x,y,w,h)的中心。我该怎么做?这是我的代码:
# 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)
编辑:注释,是的,我知道,但我只使用x和y作为临时变量,因为我不知道居中的x和y将是什么来居中文本。(I want to know how to center its CENTER to a rect, not its top left corner)
最佳答案
。
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)
关于python - pygame blitting-中心,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32673965/