Display SVG (from string) on Python Pygame

前端 未结 1 1311
逝去的感伤
逝去的感伤 2021-01-23 09:40

I have an SVG graphic represented in a string

svg_string=\'

        
1条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-23 10:44

    How to read an Scalable Vector Graphics (SVG) file is answered at SVG rendering in a PyGame application.
    There are multiple possibilities to render a SVG string.

    A simple possibility is to use svglib. Install svglib:

    pip install svglib
    

    Write a function that parses and rasterizes an SVG string and and creates a pygame.Surface object:

    from svglib.svglib import svg2rlg
    import io
    
    def load_svg(svg_string):
        svg_io = io.StringIO(svg_string)
        drawing = svg2rlg(svg_io)
        str = drawing.asString("png")
        byte_io = io.BytesIO(str)
        return pygame.image.load(byte_io)
    

    However, there seems to be a problem with transparent backgrounds. There is an issue about this topic How to make the png background transparent? #171.

    An alternative solution (which is apparently slower) is to use CairoSVG. With the function cairosvg.svg2png, an Vector Graphics (SVG) files can be directly converted to an [Portable Network Graphics (PNG)] file

    Install CairoSVG.

    pip install CairoSVG
    

    Write a function that converts a SVF file to a PNG (ByteIO) and creates a pygame.Surface object may look as follows:

    import cairosvg
    import io
    
    def load_svg(filename):
        new_bites = cairosvg.svg2png(url = filename)
        byte_io = io.BytesIO(new_bites)
        return pygame.image.load(byte_io)
    

    See also svgsurf.py^


    Minimal example:

    from svglib.svglib import svg2rlg
    import pygame
    import io
    
    def load_svg_svglib(svg_string):
        svg_io = io.StringIO(svg_string)
        drawing = svg2rlg(svg_io)
        str = drawing.asString("png")
        byte_io = io.BytesIO(str)
        svg_surf = pygame.image.load(byte_io)
        return svg_surf
    
    def display_svg_figure(screen, svg_string):
        surf = load_svg_svglib(svg_string)
        screen.blit(surf, (0, 0))
    
    background_colour = (255, 255, 255)
    (width, height) = (900, 900)
    
    screen = pygame.display.set_mode((width, height))
    pygame.display.set_caption('Display SVG')
    screen.fill(background_colour)
    
    svg_string=''
    display_svg_figure(screen, svg_string)
    
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
    
        pygame.display.flip()
    

    0 讨论(0)
提交回复
热议问题