Class for scaling images using pygame

45 Views Asked by At

I'm trying to program a class for images that can scale them up or down accordingly, but I'm having trouble trying to write out the code for this.

I am trying to use this page on the site to help, but a lot of what is being discussed there is going straight over my head and so I don't know exactly what to do: How to change an image size in Pygame?

At the minute I'm stuck trying to figure out why I keep getting this error message but I don't know where, how, or why I need to define center:

#Error
File "I:\folder\file.py", line 139, in __init__
    self.rect = self.image.get_rect(center = center)
NameError: global name 'center' is not defined


#Here is the class and function I'm trying to use:

class ScaledSprite(pg.sprite.Sprite):
    def __init__(self, centerpoint, image):
        super().__init__()
        self.originalimage = image
        self.image = image
        self.rect = self.image.get_rect(center = center)
        self.mode = 1
        self.grow = 0

    def update(self):
        if self.grow > 100:
            self.mode = -1
        if self.grow < 1:
            self.mode = 1
        self.grow += 1 * self.mode
    
        originalx, orig_y = self.original_image.get_size()
        sizex = originalx + round(self.grow)
        sizey = originaly + round(self.grow)
        self.image = pg.transform.scale(self.originalimage, (sizex, sizey))
        self.rect = self.image.get_rect(center = self.rect.center)


#Here is how I create an instance
sprite = ScaledSprite(screen.get_rect().center, pg.image.load("Logo.png"))

Any assistance with this code or an alternative way to program the scaling of images would be brilliant, and I must mention that I am relatively new to programming so any help in general would be greatly appreciated! :)

1

There are 1 best solutions below

1
BMango Gherkins On

Nevermind, I have found a much simpler way to scale images: basically, I just used "pygame.transform.scale()" to input "((image_to_be_scaled),(X_length, Y_length))", and stored this in the same variable that the original variable was in.

#From my code:
LOGO = pg.transform.scale(LOGO, (500, 300))

Credit to skrx at: How to change an image size in Pygame? :)