有关pygame.掩码函数的问题 [英] Questions regarding the pygame.mask function
本文介绍了有关pygame.掩码函数的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我阅读了pyGame的文档,但我不能清楚地理解它。我最近问了一个关于位图字体的问题,得到了一些代码作为我的答案;代码如下:
import pygame
pygame.init()
win = pygame.display.set_mode((800, 600))
font = pygame.font.Font("freesansbold.ttf", 32)
i = 0
text = "hello how are you?"
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
letter = text[i]
text_1 = font.render(letter, True, (255, 255, 255))
bw, bh = font.size(letter)
glyph_rect = pygame.mask.from_surface(text_1).get_bounding_rects()
# print(glyph_rect)
if glyph_rect:
gh = glyph_rect[0].height
print(f'letter {letter} bitmap height: {bh} glyph height: {gh}')
win.fill((0, 0, 0))
win.blit(text_1, (0, 0))
pygame.display.update()
i += 1
run = i < len(text)
pygame.quit()
所以,我的问题都在讨论中glyph_rect = pygame.mask.from_surface(text_1).get_bounding_rects()
。
pygame.mask.from_surface()
函数做什么?- 行
glyph_rect = pygame.mask.from_surface(text_1).get_bounding_rects()
做什么? - 变量
glyph_rect
返回哪些参数,这些参数的含义是什么?
推荐答案
pygame.mask.from_surface
创建pygame.mask.Mask
对象。
Surface是位图。掩码是具有Boolean值的二维数组。创建的掩码是_Surface的大小。如果表面中的相应像素不是透明的,则字段为True
,如果它是透明的,则字段为False
。
pygame.mask.Mask.get_bounding_rects
创建pygame.Rect
对象列表。每个矩形描述一个相连像素的边界区域。
如果Surface恰好包含1个连接的图像,则该图像周围将恰好有1个矩形。
请参阅示例。黑色矩形是表面矩形,红色矩形是连接组件的边界矩形:
import pygame
def getMaskRect(surf, top = 0, left = 0):
surf_mask = pygame.mask.from_surface(surf)
rect_list = surf_mask.get_bounding_rects()
surf_mask_rect = rect_list[0].unionall(rect_list)
surf_mask_rect.move_ip(top, left)
return surf_mask_rect
pygame.init()
window = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()
try:
my_image = pygame.image.load('Bomb-256.png')
except:
my_image = pygame.Surface((200, 200), pygame.SRCALPHA)
pygame.draw.circle(my_image, (0, 128, 0), (60, 60), 40)
pygame.draw.circle(my_image, (0, 0, 128), (100, 150), 40)
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pos = window.get_rect().center
my_image_rect = my_image.get_rect(center = pos)
my_image_mask_rect = getMaskRect(my_image, *my_image_rect.topleft)
window.fill((255, 255, 255))
window.blit(my_image, my_image_rect)
pygame.draw.rect(window, (0, 0, 0), my_image_rect, 3)
pygame.draw.rect(window, (255, 0, 0), my_image_mask_rect, 3)
pygame.display.flip()
pygame.quit()
exit()
这篇关于有关pygame.掩码函数的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文