PYGAME - 截图并拖拽

该博客介绍了如何利用Pygame库实现在图片上选择矩形区域进行截图,并能将截图拖拽到屏幕上的任意位置。通过监听鼠标事件,程序在用户按下鼠标时记录起点,拖动时更新截图位置,释放鼠标时完成截图并恢复初始状态。整个过程涉及图像处理和用户交互的基本原理。
摘要由CSDN通过智能技术生成

任务:实现一个需求,按下鼠标,可以选择图片上的一个矩形范围,此范围内能截图,然后再次点击鼠标可以拖拽截图到其他位置,再点击一次鼠标恢复初始状态(未做任何选择样子)

流程图:可能有些不规范,作图工具不允许

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()

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值