Pygame中get_rect( )方法——一首歌的时间学会

首先,我们需要一张图片,做我们的对象(不要想歪),是对象!对,对象!

 嗯~这个对象非常好!

然后,我们在学习rect对象时,首先了解rect对象是一个实际绘制的矩形区域。

也就是我们图片最终出现的图片的位置

get_rect ( )函数的作用是将我们的图片的位置用代码的形式告诉我们

那么我们上代码!

import pygame
import sys
pygame.init()
size = width,height = 645,645
bg = (255,255,255)

screen = pygame.display.set_mode(size)
pygame.display.set_caption("介绍rect")
girl = pygame.image.load("13.jpg")

# 获得图像的位置矩形
position = girl.get_rect()

position.right = 645

position.bottom = 645
print("left= %d,right= %d" % (position.left,position.right))
print("top= %d,bottom= %d" % (position.top,position.bottom))

# 设置为死循环,确保窗口一直显示
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
    screen.fill(bg)
    screen.blit(girl,position)
    pygame.display.flip()

这是在填满整张画布的情况,我们已经将rect的right和bottom属性设置为645

,大家可以发现,我设置的窗口size也是645*645,为什么这么设置呢?,因为我的图片的属性像素就是

 所以可以自然而然铺满整个画布。

这只是一个实例,大家一定对top,bottom,right,left有所困惑,下面为大家再次进行实例:

import pygame
import sys
pygame.init()
size = width,height = 700,700
bg = (255,255,255)

screen = pygame.display.set_mode(size)
pygame.display.set_caption("介绍rect")
girl = pygame.image.load("13.jpg")

# 获得图像的位置矩形
position = girl.get_rect()
print("left= %d,right= %d" % (position.left,position.right))
print("top= %d,bottom= %d" % (position.top,position.bottom))

# 设置为死循环,确保窗口一直显示
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
    screen.fill(bg)
    screen.blit(girl,position)
    pygame.display.flip()

运行情况为:

 可见直接蹦出一个画布上面粘贴着我们的图片,而此时输出结果为:

left= 0,right= 645
top= 0,bottom= 645
 

 这样,get_rect( )函数的作用一目了然,便是获取图片在画布上的位置

        具体top,bottom,right,left对应着哪些东西呢?

我邀请了我的不知名画师(但我觉得很ok)女友给我制作了一张图,一目了然:

图片未经允许,禁止转载。

猜你喜欢

转载自blog.csdn.net/m0_64660514/article/details/122181786