pygame blitting - 中心

问题描述 投票:2回答:3

我正在尝试在python中创建一个脚本,以便pygame绘制一个文本居中的按钮,但是当我在屏幕上进行blit时,它会向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是什么使文本居中。 (我想知道如何将它的CENTER放在一个矩形而不是它的左上角)

python pygame centering
3个回答
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, drawY)
        screen.blit(self.txt, coords)

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


0
投票

如果你想完美地居中一个物体:当你为一个物体提供Pygame坐标时,它们就是左上角的坐标。因此,我们必须将x和y坐标减半。

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

除此之外你的问题还不清楚。

© www.soinside.com 2019 - 2024. All rights reserved.