Skip to content

Instantly share code, notes, and snippets.

@zgoda zgoda/

Last active May 20, 2020
What would you like to do?
Load svg into Pygame image using pynanosvg (
from svg import Parser, Rasterizer
def load_svg(filename, scale=None, size=None, clip_from=None, fit_to=None):
"""Returns Pygame Image object from rasterized SVG
If scale (float) is provided and is not None, image will be scaled.
If size (w, h tuple) is provided, the image will be clipped to specified size.
If clip_from (x, y tuple) is provided, the image will be clipped from specified point.
If fit_to (w, h tuple) is provided, image will be scaled to fit in specified rect.
svg = Parser.parse_file(filename)
tx, ty = 0, 0
if size is None:
w, h = svg.width, svg.height
w, h = size
if clip_from is not None:
tx, ty = clip_from
if fit_to is None:
if scale is None:
scale = 1
fit_w, fit_h = fit_to
scale_w = float(fit_w) / svg.width
scale_h = float(fit_h) / svg.height
scale = min([scale_h, scale_w])
rast = Rasterizer()
req_w = int(w * scale)
req_h = int(h * scale)
buff = rast.rasterize(svg, req_w, req_h, scale, tx, ty)
image = pygame.image.frombuffer(buff, (req_w, req_h), 'ARGB')
return image

This comment has been minimized.

Copy link

kt-- commented May 9, 2019

This was not working for me - with a plain object (opaque yellow star, transparent background, no border) on a 50% grey background -

I get a very-translucent yelowish star with a cyan-coloured-ish translucent border.

Changing the pygame.image.frombuffer() 'ARGB' to 'RGBA' fixes this for me. Using Pygame 1.9.4 on Python 3.6.7 on Linux.

Bad Star ARGB bad_star
Good Star RGBA good_star

Star SVG: (I can't upload it, computer says "No")


This comment has been minimized.

Copy link

metaMMA commented Mar 1, 2020

Same issue with me. Changing it the RGBA fixed it. THanks @kt-- I would have never solved this without your comment :)


This comment has been minimized.

Copy link
Owner Author

zgoda commented Mar 1, 2020

Thanks guys. The ARGB was working for couple my images so I assumed it's common setting.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.