Skip to main content
 首页 » 编程设计

python之如何将鼠标指针居中使其成为十字准线

2025年01月19日10shangdawei

我在 GIMP 上为游戏制作了一个自定义光标,我希望鼠标以光标为中心。所以正常箭头指针的尖端位于十字准线的中心。

有什么想法吗?

我已经隐藏了另一个光标并显示了新的光标,我只是想让它居中。

请您参考如下方法:

创建一个 pygame.Rect对于光标,当 pygame.MOUSEMOTION 事件发生时,将其 center 坐标设置为鼠标位置,并将光标图像 blit 到 rect。

import pygame as pg 
 
pg.init() 
screen = pg.display.set_mode((640, 480)) 
clock = pg.time.Clock() 
# pg.mouse.set_visible(False) 
BG_COLOR = pg.Color('gray12') 
 
CURSOR_IMG = pg.Surface((40, 40), pg.SRCALPHA) 
pg.draw.circle(CURSOR_IMG, pg.Color('white'), (20, 20), 20, 2) 
pg.draw.circle(CURSOR_IMG, pg.Color('white'), (20, 20), 2) 
# Create a rect which we'll use as the blit position of the cursor. 
cursor_rect = CURSOR_IMG.get_rect() 
 
done = False 
while not done: 
    for event in pg.event.get(): 
        if event.type == pg.QUIT: 
            done = True 
        elif event.type == pg.MOUSEMOTION: 
            # If the mouse is moved, set the center of the rect 
            # to the mouse pos. You can also use pygame.mouse.get_pos() 
            # if you're not in the event loop. 
            cursor_rect.center = event.pos 
 
    screen.fill(BG_COLOR) 
    # Blit the image at the rect's topleft coords. 
    screen.blit(CURSOR_IMG, cursor_rect) 
    pg.display.flip() 
    clock.tick(30) 
 
pg.quit()