我正在尝试在程序中实现绘图框,例如当您按住鼠标按钮时,当您移动鼠标时有一个矩形。尝试用pygame rect对象来做这个,这是我到目前为止所提出的:
def mouseDown(self, button, pos):
if button == 1:
self.pressing = True
self.start = pos
def mouseUp(self, button, pos):
if button == 1:
self.pressing = False
def mouseMotion(self, buttons, pos):
if self.pressing == True:
width = abs(self.start[0] - pos[0])
height = abs(self.start[1] - pos[1])
self.box = pygame.Rect(self.start, width, height)
pygame.draw.rect(self.screen, (0,0,0), self.box, 1)
所以pos是点击的坐标,(0,0)是左上角。我尝试通过比较鼠标移动的距离来使用abs来获得大小,但是abs只返回正值,因此它不起作用。
我们如何更改此选项以使盒子选择成为可能?
答案 0 :(得分:1)
尝试类似:
def mouseMotion(self, buttons, pos):
if self.pressing == True:
diffx = self.start[0] - pos[0]
diffy = self.start[1] - pos[1]
width = abs(self.start[0] - pos[0])
height = abs(self.start[1] - pos[1])
if diffx >= 0:
if diffy >= 0:
self.box = pygame.Rect(self.start, width, height)
else:
self.box = pygame.Rect(self.start[0],pos[1], width, height)
else:
if diffy >= 0:
self.box = pygame.Rect(pos[0],self.start[1], width, height)
else:
self.box = pygame.Rect(pos, width, height)
pygame.draw.rect(self.screen, (0,0,0), self.box, 1)
答案 1 :(得分:0)
使用Calum非常有用的答案作为踏脚石,我提出了这个解决方案:
def mouseMotion(self, buttons, pos, rel):
if self.pressing == True:
diffx = self.start[0] - pos[0]
diffy = self.start[1] - pos[1]
width = abs(self.start[0] - pos[0])
height = abs(self.start[1] - pos[1])
if diffx > 0 and diffy > 0:
width = (width - (width * 2))
height = (height - (height * 2))
elif diffx > 0 and diffy <= 0:
width = (width - (width * 2))
elif diffx <= 0 and diffy > 0:
height = (height - (height * 2))
elif diffx < 0 and diffy < 0:
pass
dimensions = (width, height)
self.box = pygame.Rect(self.start, dimensions)
pygame.draw.rect(self.screen, (0,0,0), self.box, 1)
答案 2 :(得分:0)
在你的情况下我会做的是使用pygame鼠标功能。您可以使用pygame.mouse.get_rel
运行的模块,当您第一次单击“绘图区域”时,再次单击鼠标按钮时,该代码的第二次调用将为您提供两点之间的距离,并使用一些pygame.mouse.get_pos可以找到矩形的起点和终点,只需用pygame绘制它们。我希望你理解这一点,我会看看我是否可以使用代码示例。