如何实现一个裁剪工具
思路:在界面上鼠标第一次按下左键拖拽选择要裁剪的正方形
第二次鼠标左键拖拽实现将裁剪的图形移动到释放鼠标左键的位置
第三次点击的时候是取消裁剪
"""
rect(Surface, color, Rect, width=0)
# create a new surface that references its parent. Returns a new Surface that shares its pixels with its new parent.
The new Surface is considered a child of the original. Modifications to either Surface pixels will effect each other.
capture = screen.subsurface(select_rect).copy()
Pygame.Surface blit(source, dest, area=None, special_flags = 0) - > Rect:
Draws a source Surface onto this Surface. The draw can be positioned with the dest argument.Dest can
either be pair of coordinates representing the upper left corner of the source. A Rect can also be passed as
the destination and the topleft corner of the rectangle will be used as the position for the blit.
"""
import pygame
import sys
from pygame.locals import *
pygame.init()
size = width, height = 800, 600
clock = pygame.time.Clock()
screen = pygame.display.set_mode(size)
pygame.display.set_caption("裁剪小工具")
turtle = pygame.image.load("turtle.png")
background = pygame.image.load("background.jpg")
select = 0
select_rect = pygame.Rect(0, 0, 0, 0)
drag = 0
position = turtle.get_rect()
position.center = width // 2, height //2
while True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
elif event.type == MOUSEBUTTONDOWN:
if event.button == 1:
if select == 0 and drag == 0:
pos_start = event.pos
select = 1
elif select == 2 and drag == 0:
capture = screen.subsurface(select_rect).copy()
cap_rect = capture.get_rect()
drag = 1
elif select == 2 and drag == 2:
select = 0
drag = 0
elif event.type == MOUSEBUTTONUP:
if event.button == 1:
if select == 1 and drag == 0:
pos_stop = event.pos
select = 2
if select == 2 and drag == 1:
drag = 2
screen.blit(background, (0, 0))
screen.blit(turtle, position)
'''
pygame.mouse: pygame module to work with the mouse
pygame.mouse.get_pos(): get the mouse cursor position
'''
if select:
mouse_pos = pygame.mouse.get_pos()
if select == 1:
pos_stop = mouse_pos
select_rect.left, select_rect.top = pos_start
select_rect.width, select_rect.height = pos_stop[0] - pos_start[0], pos_stop[1] - pos_start[1]
'''
pygame.draw.rect() draw a rectangle shape
rect(Surface, color, Rect, width= 1) -> Rect
width是矩形边框长度为一个像素
'''
pygame.draw.rect(screen, (0, 0, 0), select_rect, 1)
if drag:
if drag == 1:
cap_rect.center = mouse_pos
screen.blit(capture, cap_rect)
pygame.display.flip()
clock.tick(30)