如何用自定义图像而不是普通块填充我的pygame.surface()?

发布于 2025-02-11 07:07:24 字数 580 浏览 1 评论 0原文

我有此代码:

import pygame

class Tile(pygame.sprite.Sprite):
    def __init__(self, pos, groups):
    super().__init__(groups)
    self.loaded_image = pygame.image.load('Folder/MyImage.png')  # I added an image and I want to
    self.image = pygame.Surface((64, 64))  # <------------------------ add it here

简单地说,我有一个pygame.surface,我想将pygame.surface的值更改为我的self.loaded_image < /代码>。是否可以?因为通常pygame.surface仅显示一个普通的块,您只能用纯色填充它,但是我希望它是自定义图像。如何?

I have this code:

import pygame

class Tile(pygame.sprite.Sprite):
    def __init__(self, pos, groups):
    super().__init__(groups)
    self.loaded_image = pygame.image.load('Folder/MyImage.png')  # I added an image and I want to
    self.image = pygame.Surface((64, 64))  # <------------------------ add it here

In simple words, I have a pygame.Surface and I want to change the pygame.Surface's value to my self.loaded_image. Is it possible? Because usually pygame.Surface just displays a plain block and you can fill it with only plain colors, but instead of a plain block, I want it to be a custom image. How?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅笑轻吟梦一曲 2025-02-18 07:07:24

首先,请注意,如果图像不是完全固体并且具有透明的背景,则需要使用Alpha频道创建一个表面(请参阅如何在pygame中具有透明背景的表面):

self.image = pygame.Surface((64, 64), pygame.SRCALPHA) 

如果图像的大小相同,只需blit图像

self.image.blit(self.loaded_image, (0, 0))

如果图像不同的大小,请使用pygame.transform.smoothscale

pygame.transform.smoothscale(self.loaded_image,
    self.image.get_size(), dest_surface=self.image)

pygame.transform.scale.scale

pygame.transform.scale(self.loaded_image, 
    self.image.get_size(), dest_surface=self.image)

First, note that if the image isn't completely solid and has a transparent background, you'll need to create a surface with an alpha channel (see How to make a surface with a transparent background in pygame):

self.image = pygame.Surface((64, 64), pygame.SRCALPHA) 

If the images are the same size, simply blit the image

self.image.blit(self.loaded_image, (0, 0))

If the images are different sizes, use pygame.transform.smoothscale

pygame.transform.smoothscale(self.loaded_image,
    self.image.get_size(), dest_surface=self.image)

or pygame.transform.scale

pygame.transform.scale(self.loaded_image, 
    self.image.get_size(), dest_surface=self.image)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文