KeyPressInteractorStyle
在vtk 中有时我们需要监听 键盘或鼠标做一些事;
1. 创建 Actor;
Sphere = vtk.vtkSphereSource()
Sphere.SetRadius(10)
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(Sphere.GetOutputPort())
actor = vtk.vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetColor(0.0, 1.0, 0.0)
2.创建 vtkRenderer vtkRenderWindow vtkRenderWindowInteractor
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
3.重写交互器 Style
class KeyPressInteractorStyle(vtk.vtkInteractorStyleTrackballCamera):
def __init__(self, parent=None):
self.parent = vtk.vtkRenderWindowInteractor()
if (parent is not None):
self.parent = parent
self.AddObserver("KeyReleaseEvent", self.keyRelease)
def keyRelease(self, obj, event):
key = self.parent.GetKeySym()
if key == 'Up':
pt = actor.GetPosition()
actor.SetPosition(pt[0],pt[1]+5,pt[2])
elif key == 'Down':
pt = actor.GetPosition()
actor.SetPosition(pt[0],pt[1]-5,pt[2])
if key == 'Left':
pt = actor.GetPosition()
actor.SetPosition(pt[0]-5,pt[1],pt[2])
elif key == 'Right':
pt = actor.GetPosition()
actor.SetPosition(pt[0]+5,pt[1],pt[2])
elif key== 'c':
# 产生随机颜色
r = vtk.vtkMath.Random()
g = vtk.vtkMath.Random()
b = vtk.vtkMath.Random()
actor.GetProperty().SetColor(r, g, b)
renWin.Render()
4.添加交互器:
iren.SetInteractorStyle(KeyPressInteractorStyle(parent=iren))
ren.AddActor(actor)