Python PyGame - 获取加载图像的大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19715251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PyGame - Getting the size of a loaded image
提问by Umut Berk Bilgic
Hello, even though you might think there was a similar question, mine is pretty different than this.
你好,尽管你可能认为有一个类似的问题,但我的和这个完全不同。
I am trying to load an image from a directory, and set my screen size (automatically) to the size of the image being loaded as "background".
我正在尝试从目录加载图像,并将我的屏幕大小(自动)设置为作为“背景”加载的图像的大小。
import pygame
import sys
from pygame.locals import *
image_resources = "C:/Users/user/Desktop/Pygame App/image_resources/"
class load:
def image(self, image):
self.image = image
return (image_resources + image)
def texture(self, texture):
self.texture = texture
return (image_resources + texture)
bg = load().image("bg_solid_black.jpg")
pygame.init()
#screen = pygame.display.set_mode((width,height),0,32)
#background = pygame.image.load(bg).convert()
#width = background.get_width()
#height = background.get_height()
The image that I loaded with my "load()" class is set to the variable "bg" and I want to use the size of whatever I load as "bg" to determine the size of the window. If you try to move
我用“load()”类加载的图像被设置为变量“bg”,我想使用我作为“bg”加载的任何东西的大小来确定窗口的大小。如果你试图移动
background = pygame.image.load(bg).convert()
width = background.get_width()
height = background.get_height()
On top of this:
在此之上:
screen = pygame.display.set_mode((width,height),0,32)
PyGame returns an error, in which it states that the display mode is not set. If I do it like this:
PyGame 返回一个错误,其中指出未设置显示模式。如果我这样做:
screen = pygame.display.set_mode((width,height),0,32)
background = pygame.image.load(bg).convert()
width = background.get_width()
height = background.get_height()
of course, this is not true, since variables "width" and "height" are not defined for the use of "pygame.display.set_mode()".
当然,这不是真的,因为变量“宽度”和“高度”不是为“pygame.display.set_mode()”的使用定义的。
I can not seem to figure this out, I though of solving through an OO manner, but I just can not seem to figure it out. Any help?
我似乎无法弄清楚这一点,我虽然通过面向对象的方式解决,但我似乎无法弄清楚。有什么帮助吗?
Thanks :)
谢谢 :)
采纳答案by furas
Before you use convert()
on any surface, screen has to be initialized with set_mode()
.
在convert()
任何表面上使用之前,屏幕必须使用set_mode()
.
You can load image and get its size before set_mode()
but convert()
has to be used afteryou initialize the display, like so:
您可以先加载图像并获取其大小,set_mode()
但convert()
必须在初始化显示后使用,如下所示:
import pygame
pygame.init()
image = pygame.image.load("file_to_load.jpg")
print(image.get_rect().size) # you can get size
screen = pygame.display.set_mode(image.get_rect().size, 0, 32)
image = image.convert() # now you can convert