简体   繁体   中英

Pygame Set Mouse Cursor from Bitmap

I'm making an image editor using pygame and I was wondering if it was possible to change the mouse cursor to something more suitable (for instance a circle or rectangle) for brushes. Pygame has a really weird way of doing it that I'm not sure would work very well. Is there a way I can write to a bitmap and then use that?

If there is a way to do it with Python generally, that would work too I suppose.

另一种选择是简单地隐藏光标,加载您喜欢的任意位图并 在光标所在的每一帧绘制它。

You can load cursors in PyGame with pygame.cursors.load_xbm -- that's black and white cursors only, of course, a well-documented limitation of PyGame, per its docs (and I quote):

Pygame only supports black and white cursors for the system.

For XBM format docs, see eg here . You can prep such files eg with the PIL library, per its docs .

Since @SapphireSun asked in a comment about another way, I'd like to present a different answer, and this is drawing the cursor manually. I guess this is what @Mizipzor suggests in his answer, so maybe this is just an elaboration.

First Hide the mouse-cursor, then every time the screen-frame is updated, "manually" paint the cursor:

pygame.mouse.set_visible(False)  # hide the cursor

# Image for "manual" cursor
MANUAL_CURSOR = pygame.image.load('finger_cursor_16.png').convert_alpha()

# In main loop ~
    ...

    # paint cursor at mouse the current location
    screen.blit( MANUAL_CURSOR, ( pygame.mouse.get_pos() ) ) 

This method allows the PyGame program to have any sort of bitmap for the cursor. There may be some trickiness around getting the "click" hot-spot in the right location, but this could be achieved by setting a transparent cursor, with the hot-spot at the position to match the custom bitmap. See the manual for details.

# transparent 8x8 cursor with the hot-spot at (4,4)
pygame.mouse.set_cursor((8,8),(4,4),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0))

I am not sure how I feel about multi-coloured cursors, but at least it's possible.

you could also just simply load a image to replace of draw something instead of it. For an example:

cursor = pygame.image.load('CURSOR IMAGE FILE HERE')
pygame.mouse.set_visible(False)  # hide the cursor
coord = pygame.mouse.get_pos()
#write this in the loop
screen.blit(cursor, coord)

If you just want to replace it with a shape you could just do this:

pygame.mouse.set_visible(False)  # hide the cursor
coord = pygame.mouse.get_pos()
pygame.draw.(shape here)(screen, (color), (coord, width, height))

Hope this helped!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM