Get rect pygame что это

от admin

Pygame: How to correctly use get_rect()

I’m trying to understand how get_rect() works. In this simple example, I have two images and want to obtain the location of the second and move the first image to the second image.

I have looked at a variety of examples online and cannot get this to work. What am I doing wrong?

1 Answer 1

First, images/pygame.Surfaces don’t have a position, so you have to store the blit position in the rect. When you call the get_rect method of a pygame.Surface, Pygame creates a new rect with the size of the image and the x, y coordinates (0, 0). To give the rect other coords during the instantiation you can pass an argument to get_rect, mostly center or topleft is used. To move the rect later, you can change any of these attributes of the rect:

Here’s an example (press a or d to change the position of the rect and thereby the blit pos of the image):

Pygame get_rect Method

Pygame get_rect Method

The main aim of this article is to demonstrate how to manipulate an image and move it around the screen using the get_rect() method from the Pygame library.

Use Pygame’s get_rect Method in Python

While working on a project or game in Pygame, one must be able to manipulate the position of the image on the screen. For example, if we want to move the player across the screen, it must change its position on the screen as the player presses a certain button.

Consider the following example:

Please enable JavaScript

Output when the two images are loaded:

Output after moving the second (blue) image on top of the right one:

As seen from the above images, we are trying to move the blue image on top of the first image. Instead of getting the desired input, we see that the blue image gets “duplicated”, and instead of completely moving on top of the red image, it is now present in its original position.

Let us see how we can fix this so that the blue image does not get “duplicated”.

the Solution to Duplicated Image When Using Pygame get_rect

Consider the following code:

Output after loading the two images:

Output after moving the blue image on top of the red image:

The main idea to achieve this is to create a rect using the get_rect method.

The initial position of the rectangle will be (0,0) . We must set it to the position of the image we wish to move.

After initializing the rectangle, change the position of the rectangle to wherever we wish the image to be. After that, redraw the background of the image to ensure that any old image instances are removed from the instance of the screen.

Once the background is drawn, we can draw the image to our desired location by calling the blit method and passing it to the image and the rectangle we created earlier. The image will be created at the coordinates of the rect .

Initialize Pygame using the init method.

Set the window by calling the display.set_mode , normally used to configure the size of the screen, adjust some flags, and color-depth.

Load the two images using load .

Fill the background with the desired color; in this case, the background was set to black using the r,g,b representation of black (0,0,0) .

Draw the images on the screen using blit , which requires the x and y coordinates to be passed. Usually given in the form of a tuple.

Use the update method to refresh the screen and show any new changes made to the canvas/screen. In this case, it will fill the background with black color and show the two loaded images.

Use the get_rect method to create a rect , and pass a tuple of coordinates to set its initial position. Otherwise, it is normally assigned the position (0,0) .

In this case, we set the position of the rectangle to the position of the image we wish to move (blue image).

Update the rectangle’s position to the new position we wish to set. Normally we set it to the position where we want the image to move.

In this case, its x-coordinate was set to the x-coordinate of the first (red) image.

Wait for a few seconds to see the changes after a delay. In this case, the time to wait was set to 2 seconds.

Redraw the image’s background; this is done to ensure that any old image instances/pixels that need to be “removed” get overwritten with the background. In this case, it was set to black.

After the background is drawn, draw the image we wish to move to its desired location. This is done using the blit method.

Two parameters get passed to in this case. First is the image that needs to be drawn, and the second is the rect we created earlier.

The rect gives the image the position to be drawn on the screen. The position is usually in the form of x-y coordinates.

To ensure that all the changes made above, such as moving the images, redrawing the background and reflecting on the screen, we call the pygame.display.update function.

The final infinite loop keeps the window running until closed manually. Each event is fetched using the pygame.event.get method, and then based on the type of event, an action is performed.

Hello! I am Salman Bin Mehmood(Baum), a software developer and I help organizations, address complex problems. My expertise lies within back-end, data science and machine learning. I am a lifelong learner, currently working on metaverse, and enrolled in a course building an AI application with python. I love solving problems and developing bug-free software for people. I write content related to python and hot Technologies.

Work with images¶

The pyagme.image module provides methods for loading and saving images. The method load() loads an image from the file system and returns a Surface object. The method convert() optimizes the image format and makes drawing faster:

Download the image bird.png to the same folder where your program resides:

The method get_rect() returns a Rect object from an image. At this point only the size is set and position is placed at (0, 0). We set the center of the Rect to the center of the screen:

To recapitulate, we are working with 3 objects:

  • screen is the Surface object representing the application window
  • img is the Surface object of the image to display
  • rect is the Rect object which is the bounding rectangle of the image

To display the image we fill the screen with a background color (GRAY). Then we blit the image, draw a red rectangle around it and finally update the screen:

Читать:
Как создать план видов расчета

Move the image with the mouse¶

At the beginning of the programm we set a boolean variable moving to False. Only when the mouse button is pressed, and when the mouse position is within the image (collidepoint) we set it to True:

When the mouse button is released, we set it to False again:

When the mouse moves, and the flag moving is True, then we move the image by the amount of relative movement (event.rel):

../_images/image0.png

This is the whole code:

Rotate and Scale the image¶

The pygame.transform module provides methods for scaling, rotating and flipping images. As we are going to modify the image img we keep the original image in a variable called img0:

In order to show the image rectangle, we add a green border to the original image:

Then we place the place the image in the center of the screen:

First we define the global variables scale and angle:

We use the R key to increment rotation by 10 degrees and (decrement if the SHIFT key is pressed). The function rotozoom() allows to combine rotation and scaling. We always transform the orignial image (img0). Repeated rotation or scaling of an image would degrade its quality:

We use the S key to increment the scale by 10% (decrease if the SHIFT key is pressed):

As the image is transformed the bounding rectangle changes size. It must be recalulated and placed at the center again:

Reset the image to the original¶

We use the O key to reset the image to its original state:

Flip the image¶

We use the H key to flip the image horizontally:

and the V key to flip the image vertically:

Detect edges with the Laplacian¶

The fonction laplacien(img) allows to detect the outline of the image:

../_images/image2.png

The fonction scale2x(img) doubles the size of a pixel:

../_images/image3.png

Transform the image with the mouse¶

In this section we show how to use the mouse to scale and rotate an image. At the beginning we import the math module:

At the beginning we store the initial mouse position:

When the mouse moves we update the mouse position mouse and calculate the x, y coordinates from the center of the image. We also calculate the center-mouse distance d

The atan2(y, x) math function allows to find the rotation angle. We need to transform radians in degrees. From the distance mouse-center we calculate the scale argument:

To finally draw the transformed image we first fille the whole screen background (GRAY), blit the transformed image, surround it with a red rectangle.

In order to give visual feedback for the mouse action when transforming an image, we

draw a green line between the center of the image and the mouse position,

Name already in use

pygame / docs / reST / ref / surface.rst

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

A pygame Surface is used to represent any image. The Surface has a fixed resolution and pixel format. Surfaces with 8-bit pixels use a color palette to map to 24-bit color.

Call :meth:`pygame.Surface()` to create a new image object. The Surface will be cleared to all black. The only required arguments are the sizes. With no additional arguments, the Surface will be created in a format that best matches the display Surface.

The pixel format can be controlled by passing the bit depth or an existing Surface. The flags argument is a bitmask of additional features for the surface. You can pass any combination of these flags:

Both flags are only a request, and may not be possible for all displays and formats.

Advance users can combine a set of bitmasks with a depth value. The masks are a set of 4 integers representing which bits in a pixel will represent each color. Normal Surfaces should not require the masks argument.

Surfaces can have many extra attributes like alpha planes, colorkeys, source rectangle clipping. These functions mainly effect how the Surface is blitted to other Surfaces. The blit routines will attempt to use hardware acceleration when possible, otherwise they will use highly optimized software blitting methods.

There are three types of transparency supported in pygame: colorkeys, surface alphas, and pixel alphas. Surface alphas can be mixed with colorkeys, but an image with per pixel alphas cannot use the other modes. Colorkey transparency makes a single color value transparent. Any pixels matching the colorkey will not be drawn. The surface alpha value is a single value that changes the transparency for the entire image. A surface alpha of 255 is opaque, and a value of 0 is completely transparent.

Per pixel alphas are different because they store a transparency value for every pixel. This allows for the most precise transparency effects, but it also the slowest. Per pixel alphas cannot be mixed with surface alpha and colorkeys.

There is support for pixel access for the Surfaces. Pixel access on hardware surfaces is slow and not recommended. Pixels can be accessed using the :meth:`get_at()` and :meth:`set_at()` functions. These methods are fine for simple access, but will be considerably slow when doing of pixel work with them. If you plan on doing a lot of pixel level work, it is recommended to use a :class:`pygame.PixelArray` , which gives an array like view of the surface. For involved mathematical manipulations try the :mod:`pygame.surfarray` module (It’s quite quick, but requires NumPy.)

Any functions that directly access a surface’s pixel data will need that surface to be lock()’ed. These functions can :meth:`lock()` and :meth:`unlock()` the surfaces themselves without assistance. But, if a function will be called many times, there will be a lot of overhead for multiple locking and unlocking of the surface. It is best to lock the surface manually before making the function call many times, and then unlocking when you are finished. All functions that need a locked surface will say so in their docs. Remember to leave the Surface locked only while necessary.

Surface pixels are stored internally as a single number that has all the colors encoded into it. Use the :meth:`map_rgb()` and :meth:`unmap_rgb()` to convert between individual red, green, and blue values into a packed integer for that Surface.

Surfaces can also reference sections of other Surfaces. These are created with the :meth:`subsurface()` method. Any change to either Surface will effect the other.

Each Surface contains a clipping area. By default the clip area covers the entire Surface. If it is changed, all drawing operations will only effect the smaller area.

Похожие статьи