我正在尝试使用Line2D在最后一个单击多边形的点和用户的鼠标之间渲染一条线。我当前的代码目前可以工作,但在渲染之间它会永远滞后,因此该行会远远落后于鼠标。当前相关代码为:

#in constructor
cid2 = self.ui.canvas2.mpl_connect('motion_notify_event', self.renderMeasureLine)

#This gets called and is laggy
def renderMeasureLine(self, mouseEvent):
    if self.measuring and mouseEvent.inaxes == self.ui.canvas2.axes and len(self.pointListX) > 0:

        if self.dotted_line in self.ui.canvas2.axes.lines:
            self.ui.canvas2.axes.lines.remove(self.dotted_line)
        self.dotted_line = Line2D([self.pointListX[-1],mouseEvent.xdata],[self.pointListY[-1],mouseEvent.ydata],
                                   color=color, axes=self.ui.canvas2.axes, ls = '--')
        self.ui.canvas2.axes.add_line(self.dotted_line)
        self.ui.canvas2.draw()

================================================================================
#mpl canvas class
class MyDynamicMplCanvas(MyMplCanvas):
    """A canvas that updates itself every second with a new plot."""
    def __init__(self, *args, **kwargs):
        MyMplCanvas.__init__(self, *args, **kwargs)
        self.colorMap = cmap.bone

    def compute_initial_figure(self):
        self.axes.imshow(self.data, cmap = cmap.bone)

    def update_figure(self, dataOverride = None):
        if self.data is not None or dataOverride is not none:
            FigureCanvas.updateGeometry(self)
            self.axes.clear()
            if dataOverride is not None:
                self.axes.imshow(dataOverride, cmap = self.getColorMap())
            else:
                self.axes.imshow(self.data, cmap = self.getColorMap())
        self.draw()

所以本质上,每次鼠标移动时,我都想更新上次单击的多边形点和当前新鼠标位置之间的虚线。这是可行的,但它是超级滞后的。有什么想法吗??
编辑:正在发生的事情的图片。虚线是慢的。

最佳答案

不要为每次鼠标移动创建新的Line2D。ALine2D可以有2个以上的点。因此,使用Line2D.set_data()来改变单个Line2D中的数据。
用数千个点绘制一个Line2D肯定比实例化和绘制数千个Line2Ds快。

def renderMeasureLine(self, mouseEvent):
    if (self.measuring and mouseEvent.inaxes == self.ui.canvas2.axes
            and len(self.pointListX) > 0):
        if self.dotted_line in self.ui.canvas2.axes.lines:
            x, y = self.dotted_line.get_data()
            x.append(mouseEvent.xdata)
            y.append(mouseEvent.ydata)
            self.dotted_line.set_data(x, y)
        else:
            self.dotted_line = Line2D(
                [self.pointListX[-1],mouseEvent.xdata],
                [self.pointListY[-1],mouseEvent.ydata],
                color=color, axes=self.ui.canvas2.axes, ls = '--')
            self.ui.canvas2.axes.add_line(self.dotted_line)

        self.ui.canvas2.blit(self.ui.canvas2.axes.bbox)
        self.ui.canvas2.draw_idle()

10-08 18:40