2015-09-19 34 views
2

我想在python中爲pygame製作一個腳本來繪製一個帶有文本居中的按鈕,但是當我在屏幕上blit時,它會傳遞給x和y我給它,而不是按比例居中的位置。我想能夠將它集中到一組(x,y,w,h)。我將如何做到這一點?這裏是我的代碼:pygame傳中 - 中心

# 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將文本居中。 (我想知道如何將它的CENTER居中,而不是它的左上角)

+0

但寬度和高度都無關,與X和Y位置。 – cdonts

+0

按比例居中的位置是什麼? – martineau

回答

5

你要使用font.size()方法來確定所呈現的文本將有多大。

喜歡的東西:

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, drayY) 
    screen.blit(self.txt, coords) 
0

如果你想完美地居中對象: 當你給一個對象的Pygame座標時,它將把它們作爲座標左上角。因此我們必須將x和y座標減半。

coords = (self.x/2, self.y/2) 
screen.blit(self.txt, coords) 

除此之外,你的問題還不清楚。

+0

這可以工作,但它只是居中文本的左上部分,並且我希望文本的中心位於x和y的中心 –

+0

'objectrect = object.get_rect()'然後將這些座標設置爲您想要的座標。 –

2

我覺得像下面這樣做是你想要的。它使用pygame.font.Font.size()來確定呈現文本所需的空間量,然後將其居中在由CenteredText實例定義的矩形區域內。

class CenteredText(object): 
    """ Centered Text Class 
    """ 
    def __init__(self, text, (x,y,w,h), color=(0,0,0)): 
     self.x, self.y, self.w, self.h = x,y,w,h 
     pygame.font.init() 
     font = pygame.font.SysFont("sans", 20) 
     width, height = font.size(text) 
     xoffset = (self.w-width) // 2 
     yoffset = (self.h-height) // 2 
     self.coords = self.x+xoffset, self.y+yoffset 
     self.txt = font.render(text, True, color) 

    def draw(self, screen): 
     screen.blit(self.txt, self.coords) 
     # for testing purposes, draw the rectangle too 
     rect = Rect(self.x, self.y, self.w, self.h) 
     pygame.draw.rect(screen, (0,0,0), rect, 1) 

考慮:

text = CenteredText('Hello world', (200,150,100,100)) 

下面是在500x400像素窗口調用text.draw(screen)結果。

screenshot of sample output