PyGame 应用程序中的 SVG 渲染.在 Pygame 2.0 之前,Pygame 不支持 SVG.那你是怎么加载的?

2022-01-18 00:00:00 python pygame widget pygame-surface svg

问题描述

在 pyGame 应用程序中,我想渲染 SVG 中描述的无分辨率 GUI 小部件.p>

我可以使用什么工具和/或库来实现这个目标?

(我喜欢 OCEMP GUI 工具包,但它的渲染似乎依赖于位图)

解决方案

这是一个完整的例子,这里结合了其他人的提示.它应该从当前目录呈现一个名为 test.svg 的文件.它在 Ubuntu 10.10、python-cairo 1.8.8、python-pygame 1.9.1、python-rsvg 2.30.0 上进行了测试.

#!/usr/bin/python导入数组导入数学进口开罗导入pygame导入 rsvg宽度 = 512高度 = 512数据 = array.array('c', chr(0) * WIDTH * HEIGHT * 4)表面 = cairo.ImageSurface.create_for_data(数据,cairo.FORMAT_ARGB32,宽度,高度,宽度 * 4)pygame.init()window = pygame.display.set_mode((WIDTH, HEIGHT))svg = rsvg.Handle(file="test.svg")ctx = cairo.Context(表面)svg.render_cairo(ctx)屏幕 = pygame.display.get_surface()image = pygame.image.frombuffer(data.tostring(), (WIDTH, HEIGHT),"ARGB")screen.blit(图像, (0, 0))pygame.display.flip()时钟 = pygame.time.Clock()而真:时钟.tick(15)对于 pygame.event.get() 中的事件:如果 event.type == pygame.QUIT:提高系统退出

In a pyGame application, I would like to render resolution-free GUI widgets described in SVG.

What tool and/or library can I use to reach this goal ?

(I like the OCEMP GUI toolkit but it seems to be bitmap dependent for its rendering)

解决方案

This is a complete example which combines hints by other people here. It should render a file called test.svg from the current directory. It was tested on Ubuntu 10.10, python-cairo 1.8.8, python-pygame 1.9.1, python-rsvg 2.30.0.

#!/usr/bin/python

import array
import math

import cairo
import pygame
import rsvg

WIDTH = 512
HEIGHT = 512

data = array.array('c', chr(0) * WIDTH * HEIGHT * 4)
surface = cairo.ImageSurface.create_for_data(
    data, cairo.FORMAT_ARGB32, WIDTH, HEIGHT, WIDTH * 4)

pygame.init()
window = pygame.display.set_mode((WIDTH, HEIGHT))
svg = rsvg.Handle(file="test.svg")
ctx = cairo.Context(surface)
svg.render_cairo(ctx)

screen = pygame.display.get_surface()
image = pygame.image.frombuffer(data.tostring(), (WIDTH, HEIGHT),"ARGB")
screen.blit(image, (0, 0)) 
pygame.display.flip() 

clock = pygame.time.Clock()
while True:
    clock.tick(15)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            raise SystemExit

相关文章