python自学——pygame基础——关于pygame中的图像位置

Python Pygame图像居中显示技巧
这篇博客介绍了如何在Pygame中将图像精确地放置在屏幕正中央。提供了两种方法,一是通过数学方法计算图像的中心点位置,二是直接利用屏幕中心坐标设置图像的center属性来实现图像居中。
部署运行你感兴趣的模型镜像

任务目标:将图片放在屏幕正中央的两种方法

方法一:数学方法

使用方法:使用 image.get_rect()方法获得图像的长(.right)和宽(.bottom),利用数学方法计算出中心点位置并赋值给图像放置位置。

实现代码:

import pygame,sys

pygame.init()
screen =pygame.display.set_mode([640,480])
pygame.display.set_caption("按键测试")
bg_color= [255,255,255]
screen.fill(bg_color)
image = pygame.image.load("D:\pythonstudy\pygameStudy\skyrobot\images\ship.bmp")
rect = image.get_rect()

while True:
    #方法一:将图片放在屏幕正中央
    rect_x = (screen.get_width()-rect.right)/2
    rect_y = (screen.get_height()-rect.bottom)/2
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
    screen.blit(image, [rect_x,rect_y])
    pygame.display.flip()

方法二:使用center属性

方法说明:获得屏幕的中心点坐标,直接把该坐标赋值给图像的中心点坐标

代码实现:

import pygame,sys

pygame.init()
screen =pygame.display.set_mode([640,480])
pygame.display.set_caption("按键测试")
bg_color= [255,255,255]
screen.fill(bg_color)
image = pygame.image.load("D:\pythonstudy\pygameStudy\skyrobot\images\ship.bmp")
rect = image.get_rect()
screen_rect = screen.get_rect()

while True:
    #方法二:将图片放在屏幕正中央
    rect.center = screen_rect.center
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
    screen.blit(image, rect)
    pygame.display.flip()
    print(rect.center)

 

您可能感兴趣的与本文相关的镜像

AutoGPT

AutoGPT

AI应用

AutoGPT于2023年3月30日由游戏公司Significant Gravitas Ltd.的创始人Toran Bruce Richards发布,AutoGPT是一个AI agent(智能体),也是开源的应用程序,结合了GPT-4和GPT-3.5技术,给定自然语言的目标,它将尝试通过将其分解成子任务,并在自动循环中使用互联网和其他工具来实现这一目标

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值