PyGame - 获取加载图像的大小

Umu*_*gic 11 python oop pygame image

您好,即使您可能认为存在类似的问题,但我的情况与完全不同.

我正在尝试从目录加载图像,并将我的屏幕大小(自动)设置为正在加载的图像的大小为"背景".

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()
Run Code Online (Sandbox Code Playgroud)

我用"load()"类加载的图像被设置为变量"bg",我想使用我加载的任何大小为"bg"来确定窗口的大小.如果你试图移动

background = pygame.image.load(bg).convert()

width = background.get_width()
height = background.get_height()
Run Code Online (Sandbox Code Playgroud)

除此之外:

screen = pygame.display.set_mode((width,height),0,32)
Run Code Online (Sandbox Code Playgroud)

PyGame返回一个错误,其中指出未设置显示模式.如果我这样做:

screen = pygame.display.set_mode((width,height),0,32)

background = pygame.image.load(bg).convert()

width = background.get_width()
height = background.get_height()
Run Code Online (Sandbox Code Playgroud)

当然,事实并非如此,因为没有为"pygame.display.set_mode()"使用变量"width"和"height".

我似乎无法弄清楚这一点,我虽然通过OO方式解决,但我似乎无法弄明白.有帮助吗?

谢谢 :)

fur*_*ras 13

convert()任何表面上使用该功能之前,需要初始化屏幕.

你可以在你面前载入图像set_mode(),得到他们的大小,然后set_mode()他们后,你已经初始化显示,像这样:

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 
Run Code Online (Sandbox Code Playgroud)

  • 你可以使用`image.get_size()`代替`image.get_rect().size`,放弃临时的`Rect`对象,在这里切一个角落。 (3认同)
  • 我可以,但是除了get_size()和一点点散文之外,与这一点没有什么实质性的区别。这将是相同的基本解决方案。;) (2认同)