python - 在 PyGame (SDL) 中使用 Cairo 时的字节顺序

我目前有一些代码使用 pycairo 绘制并通过 PyGame 渲染到 SDL 表面。这在 Linux 和 Windows 上运行良好,但 Mac 让我头疼。一切都是蓝色或粉红色字节顺序似乎是 BGRA 而不是 ARGB,我尝试使用 pygame.Surface.set_masks 和 set_shifts 无济于事。这仅在 mac (osx 10.6) 上损坏:

import cairo
import pygame

width = 300
height = 200

pygame.init()
pygame.fastevent.init()
clock = pygame.time.Clock()
sdl_surface = pygame.display.set_mode((width, height))

c_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
ctx = cairo.Context(c_surface)

while True:
    pygame.fastevent.get()
    clock.tick(30)
    ctx.rectangle(10, 10, 50, 50)
    ctx.set_source_rgba(0.0, 0.0, 0.0, 1.0)
    ctx.fill_preserve()

    dest = pygame.surfarray.pixels2d(sdl_surface)
    dest.data[:] = c_surface.get_data()
    pygame.display.flip()

我可以通过数组切片或使用 PIL 修复它,但这会降低我的帧速率。有没有办法就地或通过设置执行此操作?

最佳答案

经过大量的头发撕裂后,我有一个解决方法,它通过简单地反转数组不会对我的帧速率造成太大影响:

import cairo
import pygame

width = 300
height = 200

pygame.init()
pygame.fastevent.init()
clock = pygame.time.Clock()
sdl_surface = pygame.display.set_mode((width, height))

c_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
ctx = cairo.Context(c_surface)

while True:
    pygame.fastevent.get()
    clock.tick(30)
    ctx.rectangle(10, 10, 50, 50)
    ctx.set_source_rgba(1.0, 0.0, 0.0, 1.0)
    ctx.fill_preserve()

    dest = pygame.surfarray.pixels2d(sdl_surface)
    dest.data[:] = c_surface.get_data()[::-1]
    tmp = pygame.transform.flip(sdl_surface, True, True)
    sdl_surface.fill((0,0,0))    #workaround to clear the display
    del dest     #this is needed to unlock the display surface
    sdl_surface.blit(tmp, (0,0))
    pygame.display.flip()

我必须从临时 Surface 中删除数组和 blit 的事实似乎不正确,但这是翻转显示的唯一方法。如果有人在这里有更清洁的建议,请发表评论。

https://stackoverflow.com/questions/11640161/

相关文章:

wix - 如何在不调用安装的情况下执行 MSI 中存在的自定义操作?

python - Outlook 超链接的格式是什么?

xml - 有没有比 <!ENTITY> 更好的方法来重用 DocBook 中的复杂表格?

eclipse - 如何将当前 Eclipse 文本编辑器光标位置传递给外部工具?

ruby-on-rails - 页面加载完成后图像消失

.net - 在属性网格中添加编辑文本下拉列表

arrays - 确定网格上的点是否为 "trapped"(封闭)

python - 使用 Python 进行平台无关的文本散列

ruby-on-rails-3 - 将生成的图像文件保存为回形针附件

hibernate - JPA/JPQL : AS identifier disallowed in