0

我正在尝试在程序中实现绘图框,例如当您按住鼠标按钮时,当您移动鼠标时会出现一个矩形。试图用一个 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 只返回正值,因此它不起作用。

我们如何改变它以使框选择成为可能?

4

3 回答 3

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)
于 2013-01-28T08:25:22.930 回答
0

使用 Calums 非常有用的答案作为垫脚石,我想出了这个解决方案:

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)
于 2013-01-31T06:05:06.310 回答
0

在您的情况下,我会做的是使用 pygame 鼠标功能。您可以使用的模块是pygame.mouse.get_rel,当您第一次单击“绘图区域”并再次抬起鼠标按钮时,该代码的第二次调用将为您提供两点之间的距离,并使用一些 pygame.mouse。 get_pos 你可以找到矩形的起点和终点,然后用 pygame.get_pos 简单地绘制它们。我希望您理解这一点,我会看看我是否可以提供代码示例。

于 2013-01-31T07:29:17.467 回答