Scalable Vector Graphics 的格式是文本格式。您可以编辑 SVG 文件并添加全局比例(请参阅SVG/Transformationen)。例如:
<svg
transform="scale(2)"
...
>
自 2.0.2 起,SDL Image 支持 SVG 文件(请参阅 SDL_image 2.0)。因此,对于 pygame 2.0.1 版,pygame.image.load() 支持 SVG 文件。
当 Scalable Vector Graphic 在 pygame.Surface 中呈现时,必须进行缩放。在pygame.image.load() 中有一个scale 或size 参数会很好。然而,这样的事情还没有记录在案。
解决方法是加载 SVG 文本并添加缩放 (transform="scale(2)")。可以使用io module 将字符串加载到二进制 I/O 缓冲区中。最后,这个缓冲和缩放的 SVG 可以用pygame.image.laod 加载:
import io
def load_and_scale_svg(filename, scale):
svg_string = open(filename, "rt").read()
start = svg_string.find('<svg')
if start > 0:
svg_string = svg_string[:start+4] + f' transform="scale({scale})"' + svg_string[start+4:]
return pygame.image.load(io.BytesIO(svg_string.encode()))
bP_surface = load_and_scale_svg('bP.svg', 2)
小例子:
import pygame
import io
def load_and_scale_svg(filename, scale):
svg_string = open(filename, "rt").read()
start = svg_string.find('<svg')
if start > 0:
svg_string = svg_string[:start+4] + f' transform="scale({scale})"' + svg_string[start+4:]
return pygame.image.load(io.BytesIO(svg_string.encode()))
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
pygame_surface = load_and_scale_svg('Ice.svg', 0.4)
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.fill((127, 127, 127))
window.blit(pygame_surface, pygame_surface.get_rect(center = window.get_rect().center))
pygame.display.flip()
pygame.quit()
exit()