任务:实现一个需求,按下鼠标,可以选择图片上的一个矩形范围,此范围内能截图,然后再次点击鼠标可以拖拽截图到其他位置,再点击一次鼠标恢复初始状态(未做任何选择样子)
流程图:可能有些不规范,作图工具不允许
import pygame
import sys
from pygame.locals import *
pygame.init()
size = width, height = 1000, 800
bg = (255, 255, 255)
minions = pygame.image.load('minions.jpg')
# 0 for not select, 1 for selecting, 2 for selected
select = 0
# 0 for not drag, 1 for dragging, 2 for dragged
drag = 0
screen = pygame.display.set_mode(size)
pygame.display.set_caption('Capture and Drag a Picture')
position = minions.get_rect()
# make the pic in the center of screen
position.center = width // 2, height // 2
select_rect = pygame.Rect(0, 0, 0, 0)
while True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
elif event.type == MOUSEBUTTONDOWN:
# 1st time push down mouse
if select == 0 and drag == 0:
pos_start = event.pos
print('pos_start:', pos_start)
select = 1
# 2nd time push down mouse
elif select == 2 and drag == 0:
capture = screen.subsurface(select_rect).copy()
cap_rect = capture.get_rect()
print('cap_rect:', cap_rect)
drag = 1
# 3rd time push down mouse
elif select == 2 and drag == 2:
select = 0
drag = 0
elif event.type == MOUSEBUTTONUP:
# 1st time release mouse
if select == 1 and drag == 0:
pos_stop = event.pos
print('pos_stop:', pos_stop)
select = 2
# 2nd time release mouse
if select == 2 and drag == 1:
drag = 2
screen.fill(bg)
screen.blit(minions, position)
# the real-time select box}
if select:
if select == 1:
pos_stop = pygame.mouse.get_pos()
select_rect.left, select_rect.top = pos_start
select_rect.width = pos_stop[0] - pos_start[0]
select_rect.height = pos_stop[1] - pos_start[1]
pygame.draw.rect(screen, (0, 0, 0), select_rect, 1)
# the real-time selected image
if drag:
if drag == 1:
cap_rect.center = pygame.mouse.get_pos()
screen.blit(capture, cap_rect)
pygame.display.flip()