pygame裁剪图像的问题
import pygameimport sys
from pygame.locals import *
pygame.init()
size=width,height=600,300
bg=(255,255,255)
clock=pygame.time.Clock()
screen=pygame.display.set_mode(size)
pygame.display.set_caption("初次见面,请大家多多关照!")
turtle=pygame.image.load('悟空.jpg')
position=turtle.get_rect()
position.center = width//2,height//2
# 0-->未选择,1-->选择中,2-->选择完成
select = 0
select_rect = pygame.Rect(0,0,0,0)
# 0-->未拖拽,1-->拖拽中,2-->拖拽完成
drag = 0
while True:
for event in pygame.event.get():
if event.type == pygame.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
#第二次释放,结束拖拽
elif select ==2 and drag == 1:
drag = 2
screen.fill(bg)
screen.blit(turtle,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-pos_start,pos_stop-pos_start
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)
实时绘制选择框这里为啥框不出选择框咨询一下pygame.draw.rect(screen,(0,0,0),select_rect,1) 本帖最后由 isdkz 于 2023-4-24 21:49 编辑
您好!我注意到您的代码中有一个小错误,导致选择框不能正确显示。在定义select_rect的长和宽时(第70行),您应该使用select_rect.width和select_rect.height,而不是select_rect_height。请参阅以下修复后的代码段:
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 - pos_start, pos_stop - pos_start
pygame.draw.rect(screen, (0, 0, 0), select_rect, 1)
将此修复后的代码段替换到您的代码中,选择框应该能正确显示了。
isdkz 发表于 2023-4-24 21:47
您好!我注意到您的代码中有一个小错误,导致选择框不能正确显示。在定义select_rect的长和宽时(第70行), ...
感谢感谢,找了半天没看到
页:
[1]