是否可以在pygame中将图片放入三角形(或任何多边形)中?
在矩形上很容易做到,所以是否可以在三角形上有一个矩形并且只显示两个形状的并集?
例如。我只希望白色三角形内的部分显示在屏幕上
我尝试将图片拟合为矩形,但给出了三角形坐标,但没有成功。
pygame.maks
模块。
pygame.mask.Mask
将 pygame.Surface
转换为 pygame.mask.Mask.to_surface
。使用 setsurface
指定源图像,使用 unsetcolor
参数指定透明背景:
def clip_surface(surf, mask):
return mask.to_surface(setsurface = surf.convert_alpha(), unsetcolor = (0, 0, 0, 0))
最小示例:
import pygame
def clip_surface(surf, mask):
return mask.to_surface(setsurface = surf.convert_alpha(), unsetcolor = (0, 0, 0, 0))
def checker_image(ts, w, h, c1, c2):
surf = pygame.Surface((w, h))
[pygame.draw.rect(surf, c1 if (x+y) % 2 == 0 else c2, (x*ts, y*ts, ts, ts)) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
return surf
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
background = checker_image(40, *window.get_size(), (129, 128, 128), (96, 96, 96))
image = checker_image(20, 200, 200, (255, 128, 128), (255, 64, 64))
mask_image = pygame.Surface(image.get_size(), pygame.SRCALPHA)
pygame.draw.polygon(mask_image, (255, 255, 255), [(100, 10), (10, 190), (190, 190)])
mask = pygame.mask.from_surface(mask_image)
clipped_image = clip_surface(image, mask)
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.blit(background, (0, 0))
image_rect = clipped_image.get_rect(center = window.get_rect().center)
pygame.draw.rect(window, (0, 0, 0), image_rect, 3)
window.blit(clipped_image, image_rect)
pygame.display.flip()
pygame.quit()
exit()