How to take screenshot of certain part of screen in Pygame

拥有回忆 提交于 2019-12-01 03:32:53

问题


Is there a way I can take a screenshot of the right half of my pygame window?

I'm making a game using pygame and I need to take a snapshot of the screen but not the whole screen, just the right half.

I know of:

pygame.image.save(screen,"screenshot.jpg")

But that will include the entire screen in the image.

Is there a way I can take a screenshot of the right half of my pygame window?

Maybe by changing the area that it includes somehow? I've googled it but couldn't find anything I was thinking maybe I could use PIL to crop it, but that seems like a lot of additional work.

If it's not possible, can anyone tell me the easiest way for me to crop the picture of the whole screen?


回答1:


If you always want the screenshot to be of the same portion of the screen, you could use the subsurface. http://www.pygame.org/docs/ref/surface.html#pygame.Surface.subsurface

rect = pygame.Rect(25, 25, 100, 50)
sub = screen.subsurface(rect)
pygame.image.save(sub, "screenshot.jpg")

The subsurface would work well in this scenario because any changes to the parent surface (screen in this case) will be applied to the subsurface as well.

If you want to be able to specify an arbitrary portion of the screen to take a screenshot of (so, not the same rectangle every time) then it would probably be better to create a new surface, blit the desired portion of the screen to that surface, and then save it.

rect = pygame.Rect(25, 25, 100, 50)
screenshot = pygame.Surface(100, 50)
screenshot.blit(screen, area=rect)
pygame.image.save(screenshot, "screenshot.jpg")



回答2:


I would do something like:

example = pygame.Surface(screen.get_width()/2, 0)

Then later on when you want to take the screenshot do:

pygame.image.save(example, "example.jpg")



来源:https://stackoverflow.com/questions/17267395/how-to-take-screenshot-of-certain-part-of-screen-in-pygame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!