在pygame中绘制的图像与所给的位置不一致。

问题描述 投票:0回答:1

大家好,我正在学习pygame的基础知识,最近遇到了一个问题,我决定加载一张图片,并给它一个随机的位置,在pygame窗口中,但问题是,有时它只是不出现在窗口中。所以我在要加载图片的地方画了一个黑色指针。然后我发现黑色指针与图像不一致,因此图像没有出现在我想要的位置,所以我希望得到帮助解决这个问题。

import pygame
import random

pygame.init()

#Pygame starters
display_width = 800
display_height = 600
game_display = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Blob runner")
clock = pygame.time.Clock()
targetpng = pygame.image.load("target.png")
#Quit checker
crashed = False
#COLOURS
white = (255, 255, 255)
black = (0, 0, 0)


def draw_environment(x,y):    
    game_display.fill(white)
    #Image
    game_display.blit(targetpng,(x, y)) 
    #Black pointer
    pygame.draw.circle(game_display, black, (x, y), 5 )
    pygame.display.update()

x, y = random.randrange(0,display_width), random.randrange(0,display_height)

while not crashed:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            crashed = True
        # print(event)

    draw_environment(x,y)
    clock.tick(30)

pygame.quit()
quit()

图片。enter image description here

python image pygame draw blit
1个回答
1
投票

图片是有大小的,可能会发生图片在窗口的右边或底部。图片的来源 blit 摆放的位置 左上 的角到指定的位置。

如果您想让图像居中于以下位置 (x, y),你必须得到一个 pygame.Rect 与图像的大小 (get_rect),并将矩形的中心设置为指定的位置(关键字参数)。使用矩形来指定矩形的位置。blit 操作。

img_rect = targetpng.get_rect(center = (x, y))
game_display.blit(targetpng, img_rect) 

图像有一定的大小,因此图像的随机位置必须在 [image_size2, window_sizw - image_size2]. 宽度和高度 pygame.Surface 得以 get_width()get_height()get_size(). 例如:

img_size = targetpng.get_size()
x = random.randrange(img_size[0]//2, display_width  - img_size[0]//2)
y = random.randrange(img_size[1]//2, display_height - img_size[1]//2)

0
投票

我现在明白了@Rabbid76提供的洞察力出了什么问题。

事情是这样的,我是用油漆画的图,然后用gimp打开文件,把图像中的白色转换为alpha(类似棋盘的背景)。但问题发生在我没有清除不需要的阿尔法时,因为我以为电脑不会识别阿尔法,但事实上它识别了。

因此,当我加载图像时,图像的角落不是实际的 "目标点",而是整个图像,所以角落会在alpha上。黑点一直指向图像的角落,图像有时不显示是因为角落离边框太近,所以图像会侵入到窗口的未显示部分。

所以修复的方法是将alpha或白色背景清除到最小,然后才转换成alpha。然后按@Rabbid76说的做:D。

© www.soinside.com 2019 - 2024. All rights reserved.