我想在 Pygame 框架中鼠标点击和移动时画一条线,如果我移动鼠标很慢,它会是一条线。但是,如果我快速移动鼠标,它只是不连续的点。问题是如何在鼠标移动时绘制一条连续的线?提前致谢。
import pygame, sys
from pygame.locals import *
def main():
pygame.init()
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
mouse_position = (0, 0)
drawing = False
screen = pygame.display.set_mode((600, 800), 0, 32)
screen.fill(WHITE)
pygame.display.set_caption("ScratchBoard")
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == MOUSEMOTION:
if (drawing):
mouse_position = pygame.mouse.get_pos()
pygame.draw.line(screen, BLACK, mouse_position, mouse_position, 1)
elif event.type == MOUSEBUTTONUP:
mouse_position = (0, 0)
drawing = False
elif event.type == MOUSEBUTTONDOWN:
drawing = True
pygame.display.update()
if __name__ == "__main__":
main()
最佳答案
通过使用相同的参数 (mouse_position) 调用 pygame.draw.line
两次,您绘制的不是一条线,而是一个像素,因为 start_pos 和 end_pos 是相同的。
要获得连续的线,您需要保存最后一个位置并在它和下一个位置之间画一条线,如下所示(更改为带有 last_pos
的线):
import pygame, sys
from pygame.locals import *
def main():
pygame.init()
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
mouse_position = (0, 0)
drawing = False
screen = pygame.display.set_mode((600, 800), 0, 32)
screen.fill(WHITE)
pygame.display.set_caption("ScratchBoard")
last_pos = None
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == MOUSEMOTION:
if (drawing):
mouse_position = pygame.mouse.get_pos()
if last_pos is not None:
pygame.draw.line(screen, BLACK, last_pos, mouse_position, 1)
last_pos = mouse_position
elif event.type == MOUSEBUTTONUP:
mouse_position = (0, 0)
drawing = False
elif event.type == MOUSEBUTTONDOWN:
drawing = True
pygame.display.update()
if __name__ == "__main__":
main()
关于python - 如何在Pygame中画一条连续的线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50503609/