我有 cairo+rsvg 在 pygame 中渲染一个 .svg 文件。但是颜色通道是错误的。
但图像是:
我相信我已经交换了我的 RGBA 通道顺序,(他是粉红色的,而不是黄色的)。但不清楚它是如何工作的。这是我的代码,(否则渲染正确。)
也许pygame.display.set_mode(...)
或者pygame.image.frombuffer(...)
是相关的问题?
import pygame
from pygame.locals import *
import os
import cairo
import rsvg
import array
WIDTH, HEIGHT = 60,60
class Lion(object):
"""load+draw lion.svg"""
def __init__(self, file=None):
"""create surface"""
# Sprite.__init__(self)
self.screen = pygame.display.get_surface()
self.image = None
self.filename = 'lion.svg'
self.width, self.height = WIDTH, HEIGHT
def draw_svg(self):
"""draw .svg to pygame Surface"""
svg = rsvg.Handle(file= os.path.join('data', self.filename))
dim = svg.get_dimension_data()
self.width , self.height = dim[0], dim[1]
data = array.array('c', chr(0) * self.width * self.height * 4 )
cairo_surf= cairo.ImageSurface.create_for_data( data,
cairo.FORMAT_ARGB32, self.width, self.height, self.width * 4 )
ctx = cairo.Context(cairo_surf)
svg.render_cairo(ctx)
self.image = pygame.image.frombuffer(data.tostring(), (self.width,self.height), "ARGB")
def draw(self):
"""draw to screen"""
if self.image is None: self.draw_svg()
self.screen.blit(self.image, Rect(200,200,0,0))
class GameMain(object):
"""game Main entry point. handles intialization of game and graphics, as well as game loop"""
done = False
color_bg = Color('black') # or also: Color(50,50,50) , or: Color('#fefefe')
def __init__(self, width=800, height=600):
pygame.init()
self.width, self.height = width, height
self.screen = pygame.display.set_mode(( self.width, self.height ))
# self.screen = pygame.display.set_mode(( self.width, self.height ),0,32) # 32bpp for format 0x00rrggbb
# fps clock, limits max fps
self.clock = pygame.time.Clock()
self.limit_fps = True
self.fps_max = 40
self.lion = Lion()
def main_loop(self):
while not self.done:
# get input
self.handle_events()
self.draw()
# cap FPS if: limit_fps == True
if self.limit_fps: self.clock.tick( self.fps_max )
else: self.clock.tick()
def draw(self):
"""draw screen"""
self.screen.fill( self.color_bg )
self.lion.draw()
pygame.display.flip()
def handle_events(self):
"""handle events: keyboard, mouse, etc."""
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT: self.done = True
# event: keydown
elif event.type == KEYDOWN:
if event.key == K_ESCAPE: self.done = True
if __name__ == "__main__":
print """Keys:
ESC = quit
"""
game = GameMain()
game.main_loop()