01 操作動畫
02 關鍵代碼
- 編程:python 3.6
- 運行環境:Pycharm
- 只展示部分關鍵代碼,需要源碼的見文末鏈接
- 關鍵:一定要注意能不能運動,由于坐標軸的設置區間不同,offset的偏差值,一定要對應好。否則,鼠標無法識別圖中的點,造成無法移動的假象。
'''
設置:單點的動畫移動
'''
def __init__(self):
# 創建figure(繪制面板)、創建圖表(axes)
self.fig,self.ax = plt.subplots()
# 設置標題
self.ax.set_title('Click and drag a point to move it')
# 設置坐標軸范圍
self.ax.set_xlim((-2, 4))
self.ax.set_ylim((-2, 4))
# 設置初始值
self.x = [1,2]
self.y = [1,2]
# 繪制2D的動畫line
self.line = Line2D(self.x, self.y, ls="",
marker='o', markerfacecolor='r',
animated=True)
self.ax.add_line(self.line)
# 標志值設為none
self._ind = None
# 設置畫布,方便后續畫布響應事件
canvas = self.fig.canvas
canvas.mpl_connect('draw_event', self.draw_callback)
canvas.mpl_connect('button_press_event', self.button_press_callback)
canvas.mpl_connect('button_release_event', self.button_release_callback)
canvas.mpl_connect('motion_notify_event', self.motion_notify_callback)
self.canvas = canvas
plt.grid()
plt.show()
def get_ind_under_point(self, event):
'get the index of the vertex under point if within epsilon tolerance'
# 在公差允許的范圍內,求出鼠標點下頂點坐標的數值
xt,yt = np.array(self.x),np.array(self.y)
d = np.sqrt((xt-event.xdata)**2 + (yt-event.ydata)**2)
indseq = np.nonzero(np.equal(d, np.amin(d)))[0]
ind = indseq[0]
# 如果在公差范圍內,則返回ind的值
if d[ind] >=self.offset:
ind = None
return ind
# 鼠標移動的事件
def motion_notify_callback(self, event):
'on mouse movement'
if not self.showverts: return
if self._ind is None: return
if event.inaxes is None: return
if event.button != 1: return
# 更新數據
x,y = event.xdata, event.ydata
self.x[self._ind] = x
self.y[self._ind] = y
# 根據更新的數值,重新繪制圖形
self.line = Line2D(self.x, self.y, ls="",
marker='o', markerfacecolor='r',
animated=True)
self.ax.add_line(self.line)
# 恢復背景
self.canvas.restore_region(self.background)
self.ax.draw_artist(self.line)
self.canvas.blit(self.ax.bbox)
03 源碼分享
- 源碼已經上傳到我的上傳資料
https://download.csdn.net/download/kyrie001/11227186
辛苦研究兩天的成果,如果幫到你,希望點個贊。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
